Jump to content

Am I using while() correctly?


FinalFrontier

Recommended Posts

I use:

 

$query = "SELECT * FROM orders WHERE customeremail = joe@example.com"; $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
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 = joe@example.com"; 
//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

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.