2014-08-27 88 views
1

我正在升级我的网站以使用PDO。大部分代码工作正常,但我有一个INSERT语句,我无法工作。它适用于我的本地服务器,但不在现场。我检查过表格结构,它们是相同的。PHP PDO INSERT与预处理语句不兼容

这是我的代码

try { 

    foreach ($unique_product_line_ids AS $key => $value) { 

     $query_insertSQL = " 
      INSERT INTO tblCarts (
      date_created 
      , session_id 
      , product_line_id 
      , posted_by_id 
      , quantity 
      ) VALUES (
       :date_created 
      , :session_id 
      , :product_line_id 
      , :posted_by_id 
      , :quantity1 
      ) 
      ON DUPLICATE KEY UPDATE quantity = :quantity2 
        "; 
     $insertSQL = $conn->prepare($query_insertSQL); 

     $insertSQL->execute(array(
      ':date_created'=>$date_created 
      , ':session_id'=>$session_id 
      , ':product_line_id'=>$key 
      , ':posted_by_id'=>$_SESSION['member']['individual_id'] 
      , ':quantity1'=>$value 
      , ':quantity2'=>$value 
     )); 

     $rc_insertSQL = $insertSQL->rowCount(); 

     // close connection 
     $insertSQL->closeCursor(); 

    } 

} catch(PDOException $e) { 
     echo 'ERROR: ' . $e->getMessage(); 
} 

我在unique_product_line_ids阵列检查的价值观和他们存在的确定。我也尝试删除ON DUPLICATE KEY UPDATE行(及其相应的参数),但这没有什么区别。

我花了几个小时试图消除潜在的原因,并孤立问题没有成功。任何帮助或指针将非常感激地收到。

感谢

+0

任何错误的错误?在现场安装PDO吗? – Sal00m 2014-08-27 09:52:36

+1

只是'echo $ insertSQL-> errorInfo()' – Sal00m 2014-08-27 09:58:20

回答

3

准备语句的优点之一是,你准备一次,多次执行,所以 我将重拍你这样的代码:

try { 

    $totalInserts = 0; 

    $query_insertSQL = 
    " 
     INSERT INTO tblCarts (
       date_created 
      , session_id 
      , product_line_id 
      , posted_by_id 
      , quantity 
     ) 
     VALUES (
       :date_created 
      , :session_id 
      , :product_line_id 
      , :posted_by_id 
      , :quantity 
     ) 
     ON DUPLICATE KEY UPDATE 
      quantity = :quantity 
    "; 

    $insertSQL = $conn->prepare($query_insertSQL); 


    foreach ($unique_product_line_ids AS $key => $value) 
    { 
     $insertSQL->execute(array(
       ':date_created' => $date_created 
      , ':session_id'  => $session_id 
      , ':product_line_id'=> $key 
      , ':posted_by_id' => $_SESSION['member']['individual_id'] 
      , ':quantity'  => $value 
     )); 

     $totalInserts += $insertSQL->rowCount(); 

     /** 
     * to debug if any error 
     */ 
     var_export($conn->errorInfo()); 

     // close connection - does not need anymore while you don't 
     // prepare it multiple times 
     //$insertSQL->closeCursor(); 

    } 

} 
catch(PDOException $e) 
{ 
    echo 'ERROR: ' . $e->getMessage(); 
} 


注:

您可以根据需要多次使用一个变量, 因此无需使用:quantity1:quantity2,直到它们不同。 :quantity就够了。

要调试,如果有,您可以使用$conn->errorInfo();(连接级)或$insertSQL->errorInfo();(查询级别)

+0

George,非常感谢您的及时响应。我已经应用提示准备一次并执行多次,并将应用于我的代码中的其他实例。它没有解决我的问题,但使用errorInfo方法突出了我的问题 - 拒绝连接到数据库。真的很感谢你的帮助。约翰 – user1812108 2014-08-27 11:20:45

+1

我很高兴能够帮助你,是的,确信如果没有发现错误,就很难找出确切的问题。祝你好运 – 2014-08-27 12:35:48