php PDO 显示表数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16213695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PDO SHOW TABLES array
提问by DrDog
Just working with this function and it's not working out as planned. It is supposed to grab all table names in a database and store them in an array. However the results of the array is doubling up the array shown in the example below:
只是使用这个函数,它并没有按计划运行。它应该获取数据库中的所有表名并将它们存储在一个数组中。但是,数组的结果是将下面示例中显示的数组加倍:
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 that I am using:
我正在使用的代码:
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();
}
}
回答by Steeven Andrian Salim
to get all names of the tables 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;
}
回答by Ben Carey
You are printing the array in the while loop! This will print it each time you add an item to it from the recordset. Instead you need to print it once it has completed populating like so:
您正在 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();
}
}