PDA

View Full Version : [PHP/MySQL] Looping through an array



ZephyrWest
June 8th, 2006, 03:27 AM
Hello, I'm having trouble deciphering what is going on in the following code:


$query = "SELECT * FROM `tbl_users`";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
echo "<td>$line</td>";
foreach ($line as $col_value) { // $line is an array
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
I know what the inner foreach() loop is doing but I don't see how the while() loops works. How is "$line = mysql_fetch_array($result, MYSQL_ASSOC)" a condition? Wouldn't it return the same value everytime if at all?

And another small question, when entering queries, is it necessary to suround the name of the table with the little tick marks (`) like in the first line? Or can I use single/double/no quotes?

Thanks a bunch. :azn:

skOOb
June 8th, 2006, 08:16 AM
How is "$line = mysql_fetch_array($result, MYSQL_ASSOC)" a condition? Wouldn't it return the same value everytime if at all?$line will be filled one row at a time as an array of the values that $result gives it. So if the $result query returns 10 rows, then the while loop would loop 10 times, filling $line each time with the next row of information.


And another small question, when entering queries, is it necessary to suround the name of the table with the little tick marks (`) like in the first line? Or can I use single/double/no quotes?It isnt necessary to surround the table name with (`). You cannot use singe or double quotes on table names.

hth :beer:

bwh2
June 8th, 2006, 09:24 AM
the only time tick marks are necessary is when the table or field name is a mysql reserved word. so if you have a table named "select", you would write "select * from `select`"

ZephyrWest
June 8th, 2006, 08:56 PM
Thanks a bunch. Kirupa is full of knowledgeable and helpful people. :kommie: