dongtangze6393 2019-08-17 22:02
浏览 103

PDO为不同的查询准备了一次语句绑定参数

I am using PDO prepared statements to execute two queries:

SELECT count(*) FROM vocabulary WHERE  `type` = :type AND `lesson` = :lesson;
SELECT * FROM vocabulary WHERE  `type` = :type AND `lesson` = :lesson limit 100;

The first query to get the count works as expected and i get the row count.

$stmt = $this->connection->prepare($sql);
foreach ($params as $key => $value)
    $stmt->bindValue(":" . $key, $value, PDO::PARAM_STR);

$stmt->execute();
$count = $stmt->fetchColumn();

$sql .= " limit $limit;";
$sql = str_replace("count(*)", $columns, $sql);
$stmt = $this->connection->prepare($sql);
$stmt->execute();

$result = $stmt->fetchAll(PDO::FETCH_CLASS, $class);

But when executing the second query i get:

SQLSTATE[HY093]: Invalid parameter number: no parameters were bound

Therefore, I would like to know, if I have multiple queries where the parameters are exactly the same ,if I need to bind the same parameters again using

foreach ($params as $key => $value)
    $stmt->bindValue(":" . $key, $value, PDO::PARAM_STR);

or if there is a way to bind parameters only once.

  • 写回答

2条回答 默认 最新

  • dongwei3120 2019-08-17 22:55
    关注

    There is no need to modify your SQL like this. Your code basically comes down to this:

    $stmt = $this->connection->prepare('SELECT count(*) FROM vocabulary WHERE  `type` = :type AND `lesson` = :lesson');
    $stmt->execute($params);
    $count = $stmt->fetchColumn();
    
    $stmt = $this->connection->prepare('SELECT * FROM vocabulary WHERE  `type` = :type AND `lesson` = :lesson limit 100');
    $stmt->execute($params);
    $result = $stmt->fetchAll(PDO::FETCH_CLASS, $class);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题