【问题标题】:How to convert a sql object into a multidimensional array?如何将sql对象转换为多维数组?
【发布时间】:2014-05-25 15:51:24
【问题描述】:

我编写了这个简单的代码,并从 MySQL 表中提取了两列。然后我无法将其转换为多维数组。

所以我的表只有 2 行,而我期望它会给我 2 行和 2 列的输出。但是数组大小却变成了 4(而不是 2),而且它给temp[2]temp[3] 的打印提供了错误

<?php 
mysql_connect("localhost","root",""); //Connecting to the localhost
mysql_select_db("user"); //Selecting a database
$auth_data = mysql_query("SELECT EMAIL,UNIQUE_ID FROM authentication"); 
#Converting the object to an array
$temp = mysql_fetch_array($auth_data, MYSQL_BOTH);
echo sizeOf($temp);
echo $temp[0];
echo $temp[1];
echo $temp[2];
echo $temp[3];
?>

错误:

4abhinav.chawla@iiitb.org1

Notice: Undefined offset: 2 in C:\xampp\htdocs\test\test.php on line 11

Notice: Undefined offset: 3 in C:\xampp\htdocs\test\test.php on line 12

【问题讨论】:

  • mysql_fetch_array() 只获取一行(其列作为数组);然后它前进指针,以便下一次调用将获取下一行。您需要反复调用它,通常在像while ($row = mysql_fetch_array($auth_data)) do_something_with($row); 这样的循环中。

标签: php mysql sql arrays multidimensional-array


【解决方案1】:

您正在使用MYSQL_BOTH,因此您将数字键和字符串键都放入$temp,它只保存了您查询的第一个结果。

请使用PDO/mysqli 并删除mysql_*

【讨论】:

    【解决方案2】:
     you selected only two fields  so output will be two parameter.
    
    > select emailadn uniqueid from tablename. parameter $temp[0]; $temp [1]
    > ..................... $temp[2] $temp[3] wrong array
    

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 2016-11-28
      • 2012-11-14
      • 2013-07-03
      • 2016-10-14
      • 2017-09-27
      • 1970-01-01
      • 2017-05-05
      相关资源
      最近更新 更多