PDO显示表数组



只是使用这个函数,它没有按计划工作。它应该获取数据库中的所有表名并将它们存储在数组中。然而,数组的结果是将下面示例中所示的数组加倍:

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 ... )

我正在使用的代码:

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();
  }
}

获取所有表的名称,这是更好的

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

在while循环中打印数组!这将在每次从记录集中向其添加项时打印它。相反,您需要在它完成填充后打印它,如下所示:

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();
    }
}

最新更新