As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center 指导。
8年前关闭。
我想将一个 sql 查询结果放入一个数组中。
我尝试了下面的代码,但它显示了 $count 次的第一条记录。
显然,“$dept[$i]= $row['name'];”有问题。
但我不知道如何解决它。
有人帮忙吗?
好的,我尝试使用 mysqli 但它不起作用。
网络服务器显示:
MySQL客户端版本:4.1.22
PHP 扩展名:mysql
mysqli 可以在 mysql php 扩展中工作吗?
我建议使用 while 循环,如下所示:
如果可能的话,看看 mysqli 和 PDO,因为它们都更有效率
8年前关闭。
我想将一个 sql 查询结果放入一个数组中。
我尝试了下面的代码,但它显示了 $count 次的第一条记录。
显然,“$dept[$i]= $row['name'];”有问题。
但我不知道如何解决它。
有人帮忙吗?
$sql="SELECT name FROM system_dept ORDER BY id";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
$count=mysql_num_rows($result);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
$dept = array();
$i=0;
for($i=0;$i<$count;$i++)
{
$dept[$i]= $row['name'];
echo $dept[$i];
}
}
好的,我尝试使用 mysqli 但它不起作用。
网络服务器显示:
MySQL客户端版本:4.1.22
PHP 扩展名:mysql
mysqli 可以在 mysql php 扩展中工作吗?
最佳答案
您只获取一行以获取更多行,您需要再次调用 fetch result
所以只需将其添加到您的代码中,事情应该没问题:
for($i=0;$i<$count;$i++)
{
$dept[$i]= $row['name'];
echo $dept[$i];
$row=mysql_fetch_array($result);
}
我建议使用 while 循环,如下所示:
$sql="SELECT name FROM system_dept ORDER BY id";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
$dept = array();
while($row=mysql_fetch_array($result))
{
$dept[]=$row['name'];
echo $row['name'];
}
}
如果可能的话,看看 mysqli 和 PDO,因为它们都更有效率
关于php - 如何将sql查询结果放入数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13793724/