• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

PHP/MySQL-- Multiple queries ran in a loop not working

Al Neri

Diamond Member
I need to run multiple UPDATES in php on an SQL table - so I tried using:

$query="select Name, Age, Master.studentID from Ages, Master where Ages.studentID=Master.studentID";
$result = mysql_query($query) or die('Error123');
while ($line = @mysql_fetch_array($result))
{
$ID=$line['studentID'];
$Name=$line['Name'];
$Age=$line['Age'];
$Age=$Age+1;
$newquery="UPDATE Ages SET Age=$Age where studentID=$ID";
$result = mysql_query($newquery) or die("Error-LastU-".mysql_error());
echo "<p>Completed $Name</p>";
}
echo "<p>Totally Done!</p>";

I get back

Completed John
Totally Done!



However, if I remove the $result lines, such as

$query="select Name, Age, Master.studentID from Ages, Master where Ages.studentID=Master.studentID";
$result = mysql_query($query) or die('Error123');
while ($line = @mysql_fetch_array($result))
{
$ID=$line['studentID'];
$Name=$line['Name'];
$Age=$line['Age'];
$Age=$Age+1;
$newquery="UPDATE Ages SET Age=$Age where studentID=$ID";
echo "<p>Completed $Name</p>";
}
echo "<p>Totally Done!</p>";

I get back


Completed John
Completed Mike
Completed Bill
Completed Sally
Completed Tom
Completed Todd
Completed Jonny
Totally Done!



if I run it in PHPMyAdmin - I see there are 7 items in the Master table.

why is this just doing one of the queries and ending?
 
$result = mysql_query($newquery) or die("Error-LastU-".mysql_error()); is over writing the $result you are using in your loop conditional, therefore after you run your first update query your $result has a new value and your loop is no longer valid.
 
Back
Top