PDO SHOW TABLES Array

It just works with this function, and it doesn’t work as planned. It is supposed to capture all the table names in the database and save them in an array. However, the results of the array are doubled over the array shown in the following example:

Array ( [0] => 113340 ) 
Array ( [0] => 113340 [1] => 116516 ) 
Array ( [0] => 113340 [1] => 116516 [2] => 139431 ) 
Array ( [0] => 113340 [1] => 116516 [2] => 139431 [3] => 20731 ) 
Array ( [0] => 113340 [1] => 116516 [2] => 139431 [3] => 20731 ... )

The code I'm using is:

function itemDiscontinued($dbh, $id, $detail) {
  try {
    $tableList = array();
    $result = $dbh->query("SHOW TABLES");
    while ($row = $result->fetch(PDO::FETCH_NUM)) {
      $tableList[] = $row[0];
      print_r($tableList);
    }
  }
  catch (PDOException $e) {
    echo $e->getMessage();
  }
}
+5
source share
2 answers

to get all table names this is much better

public function list_tables()
{
    $sql = 'SHOW TABLES';
    if($this->is_connected)
    {
        $query = $this->pdo->query($sql);
        return $query->fetchAll(PDO::FETCH_COLUMN);
    }
    return FALSE;
}
+10
source

You print an array in a while loop! This will print it every time you add an item to it from a recordset. Instead, you need to print it as soon as it is filled like this:

function itemDiscontinued($dbh, $id, $detail) {
    try {   
        $tableList = array();
        $result = $dbh->query("SHOW TABLES");
        while ($row = $result->fetch(PDO::FETCH_NUM)) {
            $tableList[] = $row[0];
        }
        print_r($tableList);
    }
    catch (PDOException $e) {
        echo $e->getMessage();
    }
}
+2
source

All Articles