我想将作为 MySQL 查询结果返回的列名的所有行存储在字符串数组中。我是 PHP 的新手。我已检索到行,但如何将列的所有行存储在数组中?
我的意思是如何迭代行计数器并将列存储在数组中?还是有任何直接的函数/方法调用?请在下面查看我的代码及其在数组中存储的可能方式:
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'users';
mysql_select_db($dbname);
$result = mysql_query("SELECT users.email FROM users");
// AND THEN FINALLY STORING IN A STRING ARRAY:
$array = $result;
// OR SOMETHING LIKE:
Store($array, $result);
// OR SOMETHING LIKE:
for(int i = 0; i < $result.Rows.Count; i++)
{
if (null != $row[0])
{
$array[i] = $result[i];
}
}
// OR SOMETHING LIKE:
while($null != result.read())
{
$array.Add($result.Read());
}
最佳答案
$result = mysql_query("SELECT users.email FROM users");
while($row = mysql_fetch_array($result)){
$array[] = $row;
}
这将返回一个关联数组的数组。 $row
将包含列名称的索引以及整数索引。
例如:
echo $row['email'];
//or
echo $row[0];
最后你可以通过以下方式得到第一行:
$array[0]['email']; //or $array[0][0];
注意:不要使用 MySQL_*,因为它已从 PHP 5.5 开始弃用。请改用 MySQLi_* 或 PDO。
关于php - 如何将作为 MySQL 查询结果返回的列名的所有行存储在字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15507743/