duan0403788996 2014-05-06 22:14
浏览 105
已采纳

PHP int被MySQL转换为不同的字符串

I've got this piece of code in a Magento script:

$order = $observer->getEvent()->getOrder();
$customer_id = $order->getBillingAddress()->getCustomerId();

$idArray = array('LN123456789XZY'); // this is just arbitray sample data, the array can be any length

$prequery = "UPDATE $detailedTable SET ordered=1 WHERE customer_id=$customer_id AND image_id IN (";
$qPart = array_fill(0, count($idArray), "?");
$prequery .= implode(",", $qPart) . ")";
$query = $dbLink->prepare($prequery);
$i = 1;
foreach($idArray as $elem){
        $query->bindValue($i++, (string) $elem, PDO::PARAM_STR);                
}
$query->execute();

And what I'm seeing is the value for $customer_id is being converted into a string with a completely different value. The data types in my table for those two columns are:

customer_id => VARCHAR(64)
image_id => TEXT

So I realize that my first problem is that I'm not surrounding $customer_id with single quotes. But what’s happening because of it is an int value like 1011 in PHP is getting converted to something like 'g-608311' when it gets written to MySQL. And its happenening intermittently.

So as I'm pondering how to clean things up in my table, I'm curious how MySQL is coming up with that 'g-608311' string from the int 1011 when there's the data type mismatch?

EDIT: I updated the code snippet to show where the $customer_id value actually comes from. Also, I thought of this earlier today while pondering this issue, but when I initially ran this code, I was getting an exception with the message:

message SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value: 'g-608311' 
  • 写回答

1条回答 默认 最新

  • douxiaochun4964 2014-05-06 22:17
    关注

    Although I can't tell you exactly why you get different values due to your unquoted string input, but I can point out how ridiculous it is to use prepared statements... and then embed variables directly in the query anyway.

    Your query should be:

    $prequery = "UPDATE `literal_table_name_here` SET `ordered`=1
       WHERE `customer_id` = ?
       AND `image_id` IN (".str_repeat("?,",count($idArray)-1)."?)";
    $query = $dbLink->prepare($prequery);
    $query->bindValue(1,$customer_id);
    foreach($idArray as $i=>$elem) {
       $query->bindValue($i+2, $elem, PDO_PARAM_STR);
    }
    $query->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用