duanpai9945 2017-04-16 21:44
浏览 30
已采纳

绑定参数时MySQLi语法错误

Hi I'm working on displaying an event during a certain time period. The code is as follows. It was working when I ran the query without binding the parameters, but doing so caused me some issues. The code is as follows:

$category = $_GET['category'];
$time = $_GET['time'];
$time_ahead = strtotime("+1 month", $time);

$query = "SELECT * FROM happenings ";
$query .= "WHERE ((date_start > ? AND date_start < ?) OR (date_start < ? AND date_end > ?) OR (date_end > ? AND date_end < ?))";
if($category)
$query .= " AND category = ?";
$query .= " ORDER BY date_start ASC";

$stmt = $mysqli->prepare($query) or die ("Could not prepare statement:" . $mysqli->error);

if($category)
$stmt->bind_param('sssssss', $time, $time_ahead, $time, $time_ahead, $time, $time_ahead, $category) or die("Could not bind parameters statement:" . $stmt->error);
else
$stmt->bind_param('ssssss', $time, $time_ahead, $time, $time_ahead, $time, $time_ahead) or die("Could not bind parameters statement:" . $stmt->error);

$stmt->execute() or die("Execute failed: (" . $stmt->errno ." ". $stmt->info .") " . $stmt->error);
$result = $stmt->get_result();

The error I am getting is:

Could not run the query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND date_start < ?) OR (date_start < ? AND date_end > ?) OR (' at line 1

When I print out the query I get this

SELECT * FROM happenings WHERE ((date_start > ? AND date_start < ?) 
  OR (date_start < ? AND date_end > ?) OR (date_end > ? AND date_end < ?)) 
  ORDER BY date_start ASC

Now it's been a while, but I can't think of where the syntax is wrong. It ran fine without binding, so is there something else I need to do? I don't believe I'm using any reserved keywords or the like. I appreciate any help!

  • 写回答

1条回答 默认 最新

  • doupeng6890 2017-04-16 22:05
    关注

    For the record, the answer was guessed in the comments above.

    The code accidentally had called $mysqli->query() instead of $mysqli->prepare().

    The query() method does not recognize parameter placeholder syntax.

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

报告相同问题?

悬赏问题

  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题