存储mysql列到数组PHP


Store mysql column to array PHP

我使用它来获取一个名为"device_token"的列,并将值保存到一个数组中:

mysql_connect("localhost", "xxxx", "xxxx") or die ("Not connected");
mysql_select_db("xxxxx") or die ("no database");
$query = "SELECT xxxx_device_token FROM device_tokens";

$result_array = array();
while($row = mysql_fetch_assoc($result))
{
    $result_array[] = $row['xxxx_device_token'];
}
print_r($result_array);

但是我得到的是一个空数组,有什么问题吗?

您的代码不正确,试试这样

mysql_connect("localhost", "xxxx", "xxxx") or die ("Not connected");
mysql_select_db("xxxxx") or die ("no database");
$query = "SELECT xxxx_device_token FROM device_tokens";
$result = mysql_query($query);

$result_array = array();
while($row = mysql_fetch_assoc($result))
{
    $result_array[] = $row['xxxx_device_token'];
}

$result为空,且$query不在任何地方使用。

你需要这样写:

$result = mysql_query($query);
http://php.net/manual/en/function.mysql-query.php

您的代码不正确。您没有执行查询。您需要这样做:

mysql_connect("localhost", "xxxx", "xxxx") or die ("Not connected");
mysql_select_db("xxxxx") or die ("no database");
$result_array = array();
$query = mysql_query("SELECT xxxx_device_token FROM device_tokens");
while($row = mysql_fetch_assoc($query))
{
    $result_array[] = $row['xxxx_device_token'];
}
print_r($result_array);

但是mysql_query在新版本的PHP中被弃用了,所以你需要使用mysqli_query

试试这个,

$query = "SELECT xxxx_device_token FROM device_tokens";
$result = mysql_query($query);

$result_array = array();
while($row = mysql_fetch_assoc($result))
{
    $result_array[] = $row['xxxx_device_token'];
}

不要使用Mysql函数。不推荐使用。请移到mysql(或)PDO

while语句中有mysql_fetch_assoc($result),但没有$result的变量声明。

你必须执行你的查询:

$result = mysql_query($query);

假设这不是复制&粘贴错误,您可能遗漏了这一行:

$result = mysql_query($query);

尽量不要使用mysql_*,这是不推荐的,使用mysqli_*,理想情况下你应该使用PDO数据库连接。

那就是说你错过了这个,$result = mysql_query($query);

你忘记执行mysql查询了,像这样

$result = mysql_query($con,"SELECT * FROM Persons");