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 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错