当前位置: 移动技术网 > IT编程>开发语言>PHP > PDO::prepare讲解

PDO::prepare讲解

2019年03月16日  | 移动技术网IT编程  | 我要评论

pdo::prepare

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();
?>

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网