如何使用一个查询从 mysql 中选择多行并在 php 中使用它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6481806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select multiple rows from mysql with one query and use them in php
提问by JHyman
I currently have a database like the picture below.
我目前有一个如下图所示的数据库。
Where there is a query that selects the rows with number1 equaling 1. When using
其中有一个查询选择 number1 等于 1 的行。使用时
mysql_fetch_assoc()
in php I am only given the first is there any way to get the second? Like through a dimesional array like
在 php 中我只得到第一个有没有办法得到第二个?就像通过一个维度数组一样
array['number2'][2]
or something similar
或类似的东西
回答by Justin Aquadro
Use repeated calls to mysql_fetch_assoc. It's documented right in the PHP manual.
重复调用 mysql_fetch_assoc。它记录在 PHP 手册中。
http://php.net/manual/function.mysql-fetch-assoc.php
http://php.net/manual/function.mysql-fetch-assoc.php
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
If you need to, you can use this to build up a multidimensional array for consumption in other parts of your script.
如果需要,您可以使用它来构建多维数组,以便在脚本的其他部分使用。
回答by Nidhin David
$Query="select SubCode,SubLongName from subjects where sem=1";
$Subject=mysqli_query($con,$Query);
$i=-1;
while($row = mysqli_fetch_array($Subject))
{
$i++;
$SubjectCode[$i]['SubCode']=$row['SubCode'];
$SubjectCode[$i]['SubLongName']=$row['SubLongName'];
}
Here the while loop will fetch each row.All the columns of the row will be stored in $row
variable(array),but when the next iteration happens it will be lost.So we copy the contents of array $row
into a multidimensional array called $SubjectCode
.contents of each row will be stored in first index of that array.This can be later reused in our script.
(I 'am new to PHP,so if anybody came across this who knows a better way please mention it along with a comment with my name so that I can learn new.)
这里while循环将获取每一行。该行的所有列将存储在$row
变量(数组)中,但在下一次迭代发生时它将丢失。因此我们将数组的内容复制$row
到一个名为$SubjectCode
.contents的多维数组中每一行都将存储在该数组的第一个索引中。这可以稍后在我们的脚本中重用。(我是 PHP 的新手,所以如果有人遇到这个谁知道更好的方法,请提及它并附上我的名字的评论,以便我可以学习新知识。)