Home  >  Article  >  Backend Development  >  PHP之PDO-prepare

PHP之PDO-prepare

WBOY
WBOYOriginal
2016-06-20 12:52:501073browse

当同一个SQL多次查询(执行)时,只是每次的查询条件(数据)不一样,那么,使用prepare就对了.

它可大大减少查询(执行)时间,服务器资源消耗..


原型:

PDOStatement PDO::prepare(string query [, array driver_options])


占位符:

1,有名占位符(:named parameters)

2,问号占位符(?)

如:

INSERT INTO products SET sku = :sku, name = :name;INSERT INTO products SET sku = ?, name = ?;


绑定一个参数到指定的变量名:

bool PDOStatement::bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )//命名占位符$stmt->bindParam(':sku', $sku);$stmt->bindParam(':title', $title);//问号占位符$stmt->bindParam(1, $sku);$stmt->bindParam(2, $title);


执行步骤:

$dbh->prepare(); //准备$dbh->bindParam(); //绑定参数$dbh->execute(); //执行


查询返回字段个数:

integer PDOStatement::columnCount()

从结果集中返回下一行数据:

mixed PDOStatement::fetch([int fetch_style [, int cursor_orientation [, int cursor_offset]]])

常用fetch_style:

PDO::FETCH_ASSOC:返回一个索引为结果集列名的数组 

PDO::FETCH_BOTH(默认):返回一个索引为结果集列名和以0开始的列号的数组 

PDO::FETCH_NUM:返回一个索引为以0开始的结果集列号的数组

PDO::FETCH_OBJ:返回一个属性名对应结果集列名的匿名对象 

PDO::FETCH_BOUND:返回 TRUE ,并分配结果集中的列值给 PDOStatement::bindColumn()方法绑定PHP 变量。


返回一个包含结果集中所有行的数组

array PDOStatement::fetchAll([int fetch_style])


从结果集中的下一行返回单独的一列

string PDOStatement::fetchColumn([int column_number])

绑定列名:

boolean PDOStatement::bindColumn(mixed column, mixed &param [, int type [, int maxlen [, mixed driver_options]]])


操作事务:

开始:

boolean PDO::beginTransaction();

提交:

boolean PDO::commit();

回滚:

boolean PDO::commit()



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php?数据库查询Next article:Stark