Jump to content

While loop auto increment?


Jayel

Recommended Posts

Hi,

 

I have coded a lot in the past but only now getting into PHP and web coding in general, when I use a while loop in most other languages I need to increment some form of counter to move to the next item e.g.

while (count < 10)
{
Do something;
count + 1;
}

 

I am going through a set of tutorials that have just enlightened me to the following code when looking up a MYsql d'base:

$reults = "SELECT * FROM table";
while ($row = mysql_fetch_assoc($results)){
extract($row);
echo $tblcol1;
echo "  - ";
echo $tblcol2;
echo "<br>";
}

 

Now in fairness I have no real problem with this, if thats how you extract your results from a query then fine but I feel I am missing something and have not been able to nail it on the head.  Am I to assume that $row in the loop returns the first row from the query results, moves through the actions of the loop, returns then automatically points to the next row of the array?

 

Does that mean while($row){} where $row is a 3x3 array(for example) it would loop through this 3 times assigning the next row until the end?

 

Is there a better way to explain this?

Link to comment
Share on other sites

I do belive if you want to loop all the info you would do

 

$reults = "SELECT * FROM table";
while ($row = mysql_fetch_assoc($results)){
echo ' '.$row[tblcol1].' - '.$row[tblcol2].' <br>';
}

 

This would then loop every col1 and col2 option. like..

 

A1 - A2

B1 - B2

C1 - C2

 

Link to comment
Share on other sites

Am I to assume that $row in the loop returns the first row from the query results, moves through the actions of the loop, returns then automatically points to the next row of the array?

Basically, from the manual:

// 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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.