Jump to content

Am I using while() correctly?


FinalFrontier

Recommended Posts

I use:

 

$query = "SELECT * FROM orders WHERE customeremail = [email protected]"; $result = mysql_query($query); $row = mysql_fetch_array($result); mysql_query ($query);

 

I then use:

 

while ($row = mysql_fetch_array($result)) {
$random = rand(10000000, 99999999);
$query = "UPDATE orders SET laybypassword = ".$random." WHERE id = ".$row['id'].""; mysql_query ($query);
}

 

The first of the two rows updates, but the second doesn't. Why is that? Am I suppose to be using something like foreach()?

Link to comment
https://forums.phpfreaks.com/topic/253231-am-i-using-while-correctly/
Share on other sites

Ok, there's a number of things wrong with this, I'm going to comment on every line:

 

//this query is malformed and will throw a mysql error.  You have to quote the email address.
$query = "SELECT * FROM orders WHERE customeremail = [email protected]"; 
//this runs the query and puts the results in $result
$result = mysql_query($query); 
//this fetches the first row into $row.  YOU NEVER USE THIS RESULT
$row = mysql_fetch_array($result); 
//this runs the query a second time for no reason
mysql_query ($query);

//this loops through the result set starting at row #2, since you already fetched row #1 up there and discarded it.
while ($row = mysql_fetch_array($result)) {
$random = rand(10000000, 99999999);
        //If this field is a string password, the input really should still be quoted even though it's a number.
$query = "UPDATE orders SET laybypassword = ".$random." WHERE id = ".$row['id'].""; 
        //this line runs the above query.
        mysql_query ($query);
}

//All of this could be done in a single query without MySQL at all.

-Dan

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.