在php中prerare的用法是“PDO::prepare”,表示准备要执行的语句,并返回语句对象,其使用语法如“public PDO::prepare(string $statement, array $driver_options = array())”。
本教程操作系统:Windows10系统、PHP8.1.3版、Dell G3电脑。
php prepare的用法
PDO::prepare
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PHP 8,PECL pdo >= 0.1.0)
PDO::prepare — 准备要执行的语句,并返回语句对象
说明
1
public PDO::prepare(string $statement, array $driver_options = array()): PDOStatement为 PDOStatement::execute() 方法准备待执行的 SQL 语句。 语句模板可以包含零个或多个参数占位标记,格式是命名(:name)或问号(?)的形式,当它执行时将用真实数据取代。 在同一个语句模板里,命名形式和问号形式不能同时使用;只能选择其中一种参数形式。 请用参数形式绑定用户输入的数据,不要直接字符串拼接到查询里。
调用PDOStatement::execute()时,每一个值的参数占位标记,名称必须唯一。 除非启用模拟(emulation)模式,同一个语句里无法使用重名的参数。
注意:
参数占位符仅能字面上展示完整的数据。不能是字面的一部分,不能是关键词,不能是标识符,不能是其他任意的范围。 举例说明:不能把多个值绑到单个参数里,然后在SQL语句里用IN()查询。
如果用不同参数,通过PDO::prepare()和PDOStatement::execute() 多次调用同一个SQL语句,将提升应用的性能 —— 驱动可以让客户端/服务器缓存查询和元信息。 同时,调用PDO::prepare() 和 PDOStatement::execute()还能阻止SQL注入攻击,不需要给参数手动加引号与转义。
如果内置驱动不支持参数,PDO将模拟出参数的功能;如果驱动仅仅支持其中一种风格(命名参数和问号参数两种),也会自动重写到另外一种风格。
1
注意: The parser used for emulated prepared statements and for rewriting named or question mark style parameters supports the non standard backslash escapes for single- and double quotes. That means that terminating quotes immediately preceeded by a backslash are not recognized as such, which may result in wrong detection of parameters causing the prepared statement to fail when it is executed. A work-around is to not use emulated prepares for such SQL queries, and to avoid rewriting of parameters by using a parameter style which is natively supported by the driver.
参数
statement
必须是对目标数据库服务器有效的SQL语句模板。
driver_options
数组包含一个或多个 key=>value 键值对,为返回的PDOStatement对象设置属性。 常见用法是:设置PDO::ATTR_CURSOR为 PDO::CURSOR_SCROLL,将得到可滚动的光标。 某些驱动有驱动级的选项,在prepare时就设置。
返回值
如果数据库服务器完成准备了语句, PDO::prepare()返回PDOStatement对象。 如果数据库服务器无法准备语句, PDO::prepare() 返回false或抛出PDOException(取决于 错误处理器)。
注意:
模拟模式下的prepare语句不会和数据库服务器交互,所以PDO::prepare()不会检查语句。
范例
示例#1命名参数形式的SQL语句模板
1
2
3
4
5
6
7
8
9
10
11
<?php
/* 传入数组的值,并执行准备好的语句 */
$sql = SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour;
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(:calories => 150, :colour => red));
$red = $sth->fetchAll();
$sth->execute(array(:calories => 175, :colour => yellow));
$yellow = $sth->fetchAll();
?>
示例#2问号形式的SQL语句模板
1
2
3
4
5
6
7
8
9
10
<?php
/* 传入数组的值,并执行准备好的语句 */
$sth = $dbh->prepare(SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?);
$sth->execute(array(150, red));
$red = $sth->fetchAll();
$sth->execute(array(175, yellow));
$yellow = $sth->fetchAll();
?>
以上就是php中prerare如何运用的详细内容,更多请关注php中文网其它相关文章!
2. 分享目的仅供大家学习和交流,请不要用于商业用途!
3. 如果你也有好源码或者教程,可以到用户中心发布投稿,分享有佣金分成!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务 请大家谅解!
5. 如有链接无法下载、失效或广告,请联系站长,可领回失去的金币,并额外有奖!
6. 如遇到加密压缩包,默认解压密码为"www.77ym.top",如遇到无法解压的请联系管理员!
7. 本站部分文章、资源来自互联网,版权归原作者及网站所有,如果侵犯了您的权利,请及时联系我站删除。免责声明
暂无评论内容