0
votes

I'm creating my first php site using tutorial for reference. I can't get my head around why the following works:

while ($row = mysql_fetch_array($result)){
  echo $row[1]. " ".row[2]."<br/>";
}

Specifically, how does the loop increment to the next row?

UPDATE: Thanks to all who bothered to provide an answer, including those who implored me to RTM. My problem was not understanding how while loops work, rather simply I couldn't see how the loop increments. THE ANSWER: From the PHP docs,

mysql_fetch_array: Returns an array that corresponds to the fetched row and moves the internal data pointer ahead

I see now, all is well.

4
Read its documentation. - Yogesh Suthar
BTW PLEASE USE "mysqli_fetch_array" specifically the mysqli. - les
Like c, the function mysql_fetch_array grabs a row from a table sequentially, like a placeholder and returns 0 or false when it reaches the end. this value gets assigned to row, but its also read by the if statement - jason dancks
Please accept the answer you're most satisfied with rather than putting the answer in the question itself. - Clay

4 Answers

2
votes

You can rewrite that code to this equivalent:

$row = mysql_fetch_array($result); // fetch and advance
while ($row !== false) { // compare result against false
  echo $row[1]. " ".row[2]."<br/>";
  $row = mysql_fetch_array($result); // fetch and advance
}

An assignment yields a value which can then be used in a condition, though it's a good practice to put parentheses around the assignment:

// fetch and advance, compare fetched result against false
while (($row = mysql_fetch_array($result)) !== false) {
  echo $row[1]. " ".row[2]."<br/>";
}
1
votes

mysql_fetch_array() will take a $result and save into $row in form an array. Using while loop, your program will loop the data in the array from the beginning until the end.

By the way, your codes should be like

while ($row = mysql_fetch_array($result)){
    echo $row['someData1']. " ".row['someData2']."<br/>";
}

If you want to iterate through the index, then the code looks like following but it will print the word Array as you will print the result in "that" specific index.

$indexCounter = 0;
while ($row = mysql_fetch_array($result)){
    echo $row[$indexCounter]."<br/>";
}

Hope this helps! Thank you.

0
votes

The mysql_fetch_array take the first element of $result then is $result have elements this work... is like take cards from a deck

0
votes

Take a read though the PHP While documentation. It might also be useful to learn what mysql_fetch_array() does and how it works. After you're done reading about that, don't use the mysql_* functions again because they're deprecated. Instead, use mysqli_* or PDO.