dongshui2254 2015-08-10 20:14
浏览 26
已采纳

PHP乱序执行

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(); 
  • 写回答

1条回答 默认 最新

  • dongzhenju3015 2015-08-10 20:24
    关注

    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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题