PHP 的 PDO 准备语句:我可以多次使用一个占位符吗?

PHP#39;s PDO prepared statement: am I able to use one placeholder multiple times?(PHP 的 PDO 准备语句:我可以多次使用一个占位符吗?)
本文介绍了PHP 的 PDO 准备语句:我可以多次使用一个占位符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想执行以下查询:

选择*,(SELECT COUNT(*) FROM `tab2` WHERE `parent` = :id) AS `sum`从`tab1`哪里`id` = :id

如您所见,:id 占位符在查询中出现了两次.因此,如果我尝试使用以下命令执行此语句:

$q->execute(['id'=>$row_id]);

我收到错误:

致命错误:未捕获的异常PDOException",消息为SQLSTATE[HY093]:参数编号无效

所以我必须重写准备好的查询并使用 :id1 和 :id2 占位符执行数组,这对我来说看起来有点愚蠢.

这是在准备好的语句的多个地方使用一个占位符的唯一方法吗?

解决方案

PDO::prepare 表示

<块引用>

[y]你不能在准备好的语句中多次使用同名的命名参数标记,除非模拟模式打开.

由于通常最好关闭仿真模式(因此数据库执行准备好的语句),因此您必须使用 id_0id_1 等>

I'd like to perform the following query:

    SELECT
      *,
      (SELECT COUNT(*) FROM `tab2` WHERE `parent` = :id) AS `sum`
    FROM `tab1`
    WHERE `id` = :id

As you can see :id placeholder appeared twice in the query. So if I'd try to execute this statement with:

$q->execute(['id'=>$row_id]);

I'm receiving the error:

Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number

So I have to rewrite the prepared query and execute array with :id1 and :id2 placeholders which looks a bit stupid for me.

Is it the only way to use one placeholder in several places of the prepared statement?

解决方案

PDO::prepare states that

[y]ou cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.

Since it's generally better to leave emulation mode off (so the database does the prepared statement), you'll have to use id_0, id_1, etc.

这篇关于PHP 的 PDO 准备语句:我可以多次使用一个占位符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)