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 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀