PDO :: ATTR_EMULATE_PREPARES问题

时间:2016-04-05 00:47:53

标签: php mysql sql pdo

一旦我设置setAttribute(PDO::ATTR_EMULATE_PREPARES, false); MySQL选择查询将不再有效,有人知道为什么吗?

if($_POST)
{
    $user_checkin     = test_input($_POST['checkin']);
    $user_checkout    = test_input($_POST['checkout']);
    $user_noofpeople  = test_input($_POST['noofpeople']);
    $user_roomtype    = test_input($_POST['roomtype']);

    try
    {

        $stmt = $db_con->prepare("
            SELECT r.* 
              FROM system_apartment AS r 
             WHERE r.apartment_type = :user_roomtype
               AND r.apartment_capacity >= :user_capacity
               AND r.apartment_id 
            NOT IN
                 (
                    SELECT b.booking_apartmentid 
                      FROM system_booking AS b
                     WHERE (b.booking_date_checkout >= :user_checkin AND b.booking_date_checkin <= :user_checkout)
                        OR (b.booking_date_checkin <= :user_checkin AND b.booking_date_checkout >= :user_checkout)
                 );
        ");
        $stmt->bindParam(':user_checkin', $user_checkin, PDO::PARAM_STR);
        $stmt->bindParam(':user_checkout', $user_checkout, PDO::PARAM_STR);
        $stmt->bindParam(':user_roomtype', $user_roomtype, PDO::PARAM_STR);
        $stmt->bindParam(':user_capacity', $user_noofpeople, PDO::PARAM_INT);
        $stmt->execute();
        $count = $stmt->fetchAll();
        $count = count($count);

        if($count==0){
            echo "noapartments"; //  not available
        }
        else{
            echo "searchcomplete"; //  not available
        }

    }
    catch(PDOException $e){
        echo $e->getMessage();
    }
}

在将属性设置为false之前,代码工作正常。

1 个答案:

答案 0 :(得分:0)

如果禁用PREPARE仿真,则无法多次使用同一占位符。您需要每次使用:user_checkin:user_checkout个不同的占位符。

    $stmt = $db_con->prepare("
        SELECT r.* 
          FROM system_apartment AS r 
         WHERE r.apartment_type = :user_roomtype
           AND r.apartment_capacity >= :user_capacity
           AND r.apartment_id 
        NOT IN
             (
                SELECT b.booking_apartmentid 
                  FROM system_booking AS b
                 WHERE (b.booking_date_checkout >= :user_checkin AND b.booking_date_checkin <= :user_checkout)
                    OR (b.booking_date_checkin <= :user_checkin2 AND b.booking_date_checkout >= :user_checkout2)
             );
    ");
    $stmt->bindParam(':user_checkin', $user_checkin, PDO::PARAM_STR);
    $stmt->bindParam(':user_checkout', $user_checkout, PDO::PARAM_STR);
    $stmt->bindParam(':user_checkin2', $user_checkin, PDO::PARAM_STR);
    $stmt->bindParam(':user_checkout2', $user_checkout, PDO::PARAM_STR);
    $stmt->bindParam(':user_roomtype', $user_roomtype, PDO::PARAM_STR);
    $stmt->bindParam(':user_capacity', $user_noofpeople, PDO::PARAM_INT);