list all tables in a database with MySQLi

后端 未结 4 1796
梦谈多话
梦谈多话 2021-02-14 04:13

I have looked around and still can\'t find how to list all my tables in a database. is it possible with MySQLi?

Thanks.

相关标签:
4条回答
  • 2021-02-14 04:43

    I'd try something like:

    function get_tables()
    {
      $tableList = array();
      $res = mysqli_query($this->conn,"SHOW TABLES");
      while($cRow = mysqli_fetch_array($res))
      {
        $tableList[] = $cRow[0];
      }
      return $tableList;
    }
    

    You might also be interested in skimming this: https://devzone.zend.com/13/php-101-part-8-databases-and-other-animals_part-2/ (EDIT: this link refers to mysql API and not mysqli, but most calls do have a mysqli parallel).

    HTH

    0 讨论(0)
  • 2021-02-14 04:52

    Using PHP 5.5 or later, a simple solution is using PHP's built-in array_column() function.

    $link = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);
    $listdbtables = array_column(mysqli_fetch_all($link->query('SHOW TABLES')),0);
    
    0 讨论(0)
  • 2021-02-14 04:52

    here is little example

    class database {
        public $connection;
    
        function __construct() {
            $this->connection = mysqli_connect(DBHOST,
                                               DBUSER,
                                               DBPASS,
                                               DBNAME) or 
            die('Database Connection Error: '.mysqli_connect_error());  
        }
    
        public function close_database() { 
            return mysqli_close($this->connection); 
        }
        public function query($query) {
            $query = mysqli_query($this->connection ,$query) or die($this->show_errors('Query Execution Error: '.mysqli_error($this->connection),'E'));
            return $query;  
        }
        public function fetch_assoc($query) {
            $query = mysqli_fetch_assoc($query);
            return $query;  
        }
    }
    
    $db = new database();
    $query = $db->query("SHOW TABLES FROM DATABASENAME");
    $db->fetch_assoc($query);
    
    0 讨论(0)
  • 2021-02-14 05:06

    There are many ways.

    SHOW TABLES
    

    Is the most simple SQL statement for doing that. You can also take a look at INFORMATION_SCHEMA.TABLES if you want to have more details or do some filtering or such.

    SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA LIKE 'your_database';
    
    0 讨论(0)
提交回复
热议问题