douhuitan5863 2016-02-16 16:30
浏览 39
已采纳

PHP转义存储过程参数

I have litle problem with stored procedure when assign parameter value. Am assigning value as a date '2016-05-01','2016-07-30'

Procedure work fine when i manual enter date like this:

CALL calculateSeasonPrice(3, '2016-05-01','2016-07-30')

success return array with data.

But problem is when i assign variables as arguments

$carId = 3;
$sDate = '2016-05-01';
// and
$eDate = '2016-07-30';

$price = $db->query("CALL calculateSeasonPrice({$carID},{$sDate},{$eDate})"); // problem

return empty array

Does i need to escape this two variales. I also try this and not work!

$price = $db->query("CALL calculateSeasonPrice(".$carID.",".$sDate.",".$eDate.")"); // This work

What i miss here?

  • 写回答

1条回答 默认 最新

  • dpq755012465 2016-02-16 16:34
    关注

    In the queries where you try to use variables you're forgetting the quotes for the values:

    $price = $db->query("CALL calculateSeasonPrice('$carID','$sDate','$eDate')");
    

    If you used prepared statements you would not have these kinds of problems. You can learn more about prepared statements for PDO and MySQLi.

    PDO Example:

    $carId = 3;
    $sDate = '2016-05-01';
    $eDate = '2016-07-30';
    
    $price = "CALL calculateSeasonPrice(?,?,?)";
    $queryResults = $dbh->prepare($price);
    $queryResults->execute(array($carId, $sDate, $eDate));
    

    MySQLi Example:

    $price = "CALL calculateSeasonPrice(?,?,?)";
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param("iss", $carId, $sDate, $eDate);
    $stmt->execute();
    

    Fundamentally these are not very different, but there are some subtle elements that you'll want to get used to, depending on the API you choose for your work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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时遇到的编译问题