使用之间的区别?和:param在prepare语句中 [英] Differences between using ? and :param in prepare statement

查看:73
本文介绍了使用之间的区别?和:param在prepare语句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要选择Id = 30所在的记录.准备好的语句允许两种方式绑定参数:

Let's say I want to select records where Id = 30. Prepared statements allow two ways of binding parameters:

问号

$id = 30;
$q = $conn->prepare("SELECT * FROM pdo_db WHERE id > ?");
$q->execute(array($id));  // Here above ID will be passed 

命名参数

$sth = $conn->prepare("SELECT `id`, `title` FROM `pdo_db` WHERE `id` > :id");
$sth->execute(array(
  ':id' => 30
));

两者都能正常工作并给出准确的结果,但是我无法获得两者之间的确切差异,也无法何时使用一个或另一个?

Both are working fine and give accurate results but I am not able to get the exact differences between these two nor when I should use one or another?

推荐答案

问号参数称为 positioning 参数.

使用:定义的参数和名称称为命名的参数.

Parameters defined with : and a name are called named parameters.

规则是您不能在准备好的语句中混用两者.

The rule is that you can't mix the two in your prepared statement.

位置参数的工作方式很简单-如果您有两个位置参数,则可以指定一个包含两个元素的数组.数组值将按照它们在数组中出现的顺序进行绑定.

Positional parameters work in a simple way - if you have two positional parameters, you can specify an array with two elements. Array values will be bound in order as they appear in the array.

命名参数有点棘手,它们不必绑定就可以出现.您也可以在语句中多次重复一个命名参数,但是只能绑定一次以传递值-当通过$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);将PDO设置为仿真时,最后一部分才起作用.

Named parameters are a bit trickier, they don't have to be bound in order they appear. You can also repeat one named parameter multiple times in the statement, but you can bind it only once to pass the value - that last part works when PDO is set to emulation via $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);.

这篇关于使用之间的区别?和:param在prepare语句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆