开发者

How to select multiple rows from mysql with one query and use them in php

开发者 https://www.devze.com 2023-03-15 05:35 出处:网络
I currently have a database like the picture below. Where there is a query that selects the rows with number1 equaling 1. When using

I currently have a database like the picture below.

How to select multiple rows from mysql with one query and use them in php

Where there is a query that selects the rows with number1 equaling 1. When using

mysql_fetch_assoc()

in php I am o开发者_如何学编程nly given the first is there any way to get the second? Like through a dimesional array like

array['number2'][2] 

or something similar


Use repeated calls to mysql_fetch_assoc. It's documented right in the PHP manual.

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.


$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.)


This is another easy way

$sql_shakil ="SELECT app_id, doctor_id FROM patients WHERE doctor_id = 201 ORDER BY ABS(app_id) ASC";
if ($result = $con->query($sql_shakil)) {

while ($row = $result->fetch_assoc()) {
    printf ("%s (%s)\n", $row["app_id"], $row["doctor_id"]);
}

Demo Link


It looks like the complete solution has not been suggested yet

$Query="select SubCode,SubLongName from subjects where sem=1";
$Subject=mysqli_query($con,$Query);
$Rows = array ();
while($row = mysqli_fetch_array($Subject))
{
    $Rows [] = $row;
}

The $Rows [] = $row appends the row to the array. The result is a multidimensional array of all rows.

0

精彩评论

暂无评论...
验证码 换一张
取 消