Reputation: 342
I am writing a PHP script and it appears that I'm having issues with out of order execution. I have a for loop that checks the existence of records in a table with an insert following it. The idea was to keep the insert from happening if the for loop finds an existing record. However, when I run the following script, it would appear that my insert statement is being executed either during or before the for loop since I'm still getting record insertion into reservations
even when a matching record exists in reservedTickets
that should halt execution. What is the best way to handle this?
PHP:
for ($i=1; $i<=$_POST['numTickets']; $i++)
{
$checkTID = $_POST["tid".$i];
if (mysql_fetch_assoc(mysql_query("SELECT EXISTS(SELECT 1 FROM reservedTickets WHERE tid=".$checkTID.") AS 'exists';"))['exists'] == 1)
{
header("Location: http://10.12.76.201/reservations/");
}
}
mysql_query("INSERT INTO reservations (aid, approval) VALUES (".$_POST['aid'].", 0);");
$reservationID = mysql_insert_id();
Upvotes: 2
Views: 301
Reputation: 69937
The execution is happening after the loop because calling the header()
function alone will not halt execution. Rather, it tells PHP to append that response header when the request is complete but doesn't stop any code below it from running.
You should use one of the following constructions:
for ($i=1; $i<=$_POST['numTickets']; $i++)
{
$checkTID = $_POST["tid".$i];
if (mysql_fetch_assoc(mysql_query("SELECT EXISTS(SELECT 1 FROM reservedTickets WHERE tid=".$checkTID.") AS 'exists';"))['exists'] == 1)
{
header("Location: http://10.12.76.201/reservations/");
exit; // STOP script execution, and send the header
}
}
or
$found = false;
for ($i=1; $i<=$_POST['numTickets']; $i++)
{
$checkTID = $_POST["tid".$i];
if (mysql_fetch_assoc(mysql_query("SELECT EXISTS(SELECT 1 FROM reservedTickets WHERE tid=".$checkTID.") AS 'exists';"))['exists'] == 1)
{
$found = true;
break; // exit the for loop
}
}
if (!$found) {
mysql_query("INSERT INTO reservations (aid, approval) VALUES (".$_POST['aid'].", 0);");
$reservationID = mysql_insert_id();
}
Upvotes: 3