pdo::prepare — 准备要执行的sql语句并返回一个 pdostatement 对象(php 5 >= 5.1.0, pecl pdo >= 0.1.0)
说明
语法
public PDOStatement PDO::prepare ( string $statement [, array $driver_options = array() ] )
为 PDOStatement::execute() 方法准备要执行的SQL语句,SQL语句可以包含零个或多个命名(:name)或问号(?)参数标记,参数在SQL执行时会被替换。
你不能在 SQL 语句中同时包含命名(:name)或问号(?)参数标记,只能选择其中一种风格。
预处理 SQL 语句中的参数在使用PDOStatement::execute()方法时会传递真实的参数。
参数
statement:合法的SQL语句。
driver_options:此数组包含一个或多个 key=>value 对来设置 PDOStatement 对象的属性, 最常使用到是将PDO::ATTR_CURSOR值设置为PDO::CURSOR_SCROLL来请求一个可滚动游标。
返回值
如果成功,PDO::prepare()返回PDOStatement对象,如果失败返回 FALSE 或抛出异常 PDOException 。
实例
使用命名(:name)参数来准备SQL语句
<?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(); ?>
使用问号(?)参数来准备SQL语句
<?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(); ?>
以上就是mysql PDO::prepare用法详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号