Search code examples
mysqlpdo

show tables get only the last name of table


I'm trying to show the name of table in my database. I write this code :

   function affiche_liste()
{   
$db=new PDO('mysql:host=localhost;dbname=testf','root','');
    $result = $db->query("SHOW TABLES");
       foreach($result->fetch(PDO::FETCH_NUM) as $data) {
            $tableList = $data[0];
        }
        return $tableList;
}

It give to me only the last table ?


Solution

  • For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function. The following function () returns an array containing all rows in the result set.

    function queryAll($db,$query){  
        $sth = $db->query($query);
        $result = $sth->fetchAll(PDO::FETCH_NUM);
        return $result;
    }
    

    For a simple query without parameters and the SQL hard coded you can use a generic function passing the connection and SQL to the function. The following function () returns an array containing all rows in the result set.

    function queryAll($db,$query){  
        $sth = $db->query($query);
        $result = $sth->fetchAll(PDO::FETCH_NUM);
        return $result;
    }
    
    $db=new PDO('mysql:host=localhost;dbname=testf','root',''); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $query = "SHOW TABLES";
    $tables = queryAll($db,$query);
    print_r($tables);