Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through a PHP array containing data returned from MySQL?

Tags:

loops

sql

php

Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:

    • username: bob
    • password: bob
    • report: 1
    • username: bob
    • password: bob
    • report: 2

I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:

$thisrow = mysql_fetch_row($result);

I need to get every field from every row. How should I go about doing this?

$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'"; 
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1);  //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];

Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.

like image 749
The Digital Ninja Avatar asked Jan 22 '26 13:01

The Digital Ninja


2 Answers

mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:

while ($row = mysql_fetch_row($result))
{
    // code
}
like image 77
hbw Avatar answered Jan 24 '26 02:01

hbw


Use a loop, and use mysql_fetch_array() instead of row:

while($row = mysql_fetch_array($result)) {
   echo "Study: " . $row[1] . " - " . $row[5];
   // but now with mysql_fetch_array() you can do this instead of the above
   // line (substitute userID and username with actual database column names)...
   echo "Study: " . $row["userID"] . " - " . $row["username"];
}
like image 44
John Rasch Avatar answered Jan 24 '26 01:01

John Rasch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!