如何使用 PHP 获取列中的所有值?

2022-08-30 14:12:20

我一直在到处寻找这个,但仍然找不到解决方案:如何从mySQL列中获取所有值并将其存储在数组中?

例如:表名称:客户 列名称:ID,行名称数:5

我想获取此表中所有5个名称的数组。我该怎么做?我正在使用PHP,我试图只是:

SELECT names FROM Customers

,然后使用

mysql_fetch_array

PHP 函数将这些值存储在数组中。


答案 1

这是使用PDOmysqli执行此操作的简单方法

$stmt = $pdo->prepare("SELECT Column FROM foo");
// careful, without a LIMIT this can take long if your table is huge
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($array);

或者,使用 mysqli

$stmt = $mysqli->prepare("SELECT Column FROM foo");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
    $array[] = $row['column'];
}
print_r($array);

Array
(
    [0] => 7960
    [1] => 7972
    [2] => 8028
    [3] => 8082
    [4] => 8233
)

答案 2

请注意,这个答案已经过时了!自 PHP7 起,mysql 扩展不再开箱即用。如果你想在PHP7中使用旧的mysql函数,你必须从PECL编译ext/mysql。有关更多最新解决方案,请参阅其他答案。


这将起作用,请参阅此处的更多文档:http://php.net/manual/en/function.mysql-fetch-array.php

$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row['names'];  
}
// now $storeArray will have all the names.