简体   繁体   English

SQL表列到数组

[英]SQL Table column to array

How do I get the values in one column to an array? 如何将一列中的值获取到数组? In the example table I want all the names in the column "NAME" to "my_array". 在示例表中,我希望“ NAME”列中的所有名称都为“ my_array”。

Ex. (my_table)
|ID|NAME   |
------------
|1 |my_name|
------------
|2 |my_name|
--------------------------------------------------

$con=mysqli_connect("localhost","root","","my_db");
if (mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM my_table");

$my_array = array();
$column = 'NAME';

$i=1;    
while($row = mysql_fetch_array($result)){
    $my_array [$i]=$row[$column];
    $i++;
}

mysqli_close($con);

First, dont set $i = 1 , because an array starts at 0, not at 1. Than, I would use mysql_fetch_assoc() instead of mysql_fetch_array() . 首先,不要设置$i = 1 ,因为数组从0开始而不是从1开始。然后,我将使用mysql_fetch_assoc()而不是mysql_fetch_array()

$i=0;    
while($row = mysql_fetch_assoc($result)){
    $my_array[$i] = $row[$column];
    $i++;
}

It looks like your code should work, if you are just looking for a more efficient way to do it, have a look at searching databases with PDO and use can use 看起来您的代码应该可以工作,如果您只是在寻找一种更有效的方式,请看一下使用PDO搜索数据库,并且可以使用

$conn = new PDO('mysql:dbname='.$database.';host='.$host, $username, $password);
$stmt = $conn->prepare('SELECT ID FROM my_table'); 
$stmt->execute();    
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$myarray = $stmt->fetchAll();
echo $myarray[0]['ID'].','.$myarray[1]['ID']; //etc

If you are after just one column, just select that one not * if you are after more than one. 如果仅在一列之后,则选择多于一列而不是*。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM