我正在编写一个PHP脚本,看起来我在执行无序的过程中遇到了问题。我有一个for循环,它检查表中是否存在记录,并在表后面插入。如果for循环找到了一个现有的记录,那么这个想法就是防止插入发生。但是,当我运行以下脚本时,我的insert语句似乎是在for循环期间或之前执行的,因为即使在应该停止执行的reservations中存在匹配的记录时,我仍然会将记录插入到reservedTickets中。处理这件事最好的方法是什么?
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(); 发布于 2015-08-10 20:24:32
执行是在循环之后进行的,因为单独调用header()函数不会停止执行。相反,它告诉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/");
exit; // STOP script execution, and send the header
}
}或
$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();
}https://stackoverflow.com/questions/31928332
复制相似问题