Blogger Information
Blog 7
fans 0
comment 0
visits 8112
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
pdo方法的使用
dongfeng的博客
Original
993 people have browsed it

作业



1. PDO连接数据库的过程与参数设置

2. 如果创建PDO预处理对象: prepare()方法

3. bindParam()与bindValue()

4. execute()直接传参

5. fetch() 和 fetchAll()的区别与联系

6. bindColumn()的功能

pdo的环境

在windows环境下,在php.ini在中加载 extension=php_pdo.dll  对mysql 加载extension=php_pdo_mysql.dll;

链接数据库就是创建pdo对象

__construct()

$dbms='mysql';

$dbName='Db_aaa';

$usr='root';

$passWord='root';

$host='localhost';

$pdo= new pdo($dsn,$usr,$password);

$dsn="$dbms:host=$host;dbname=$dbName";



创建PDO预处理对象: prepare()方法:

如果执行多次查询1)pdo::prepare(string satement);返回一个PDOStatment对象2)bool PDOStatement::execute()执行查询返回结果集

如果执行一次查询,直接用pdo::query()返回一个PDOStatment对象 (结果集)


预处理对象的fetch(pdo::FETCH_ASSOC)

while($res->fetch(PDO::FETCH_ASSOC)){}

预处理对象的fetchall(pdo::FETCH_ASSOC)

for($i=0,$i<count($res),$i++){}

预处理对象的fetchcolumn() 获取下一行指定列的值

$res->fetchColumn(0);


bindParam()与bindValue() bindcloumn


<?php

/*  通过绑定的 PHP 变量执行一条预处理语句 */

$weight = 150;

$color = 'red';

$sth = $dbh->prepare('SELECT name, color, weight

FROM fruit

WHERE weight < ? AND color = ?');

$sth->bindParam(1, $weight, PDO::PARAM_INT);

$sth->bindParam(2, $color, PDO::PARAM_STR, 12);

$sth->execute();

?>

<?php

/* 通过绑定的 PHP 变量执行一条预处理语句 */

$weight = 150;

$color = 'red';

$sth = $dbh->prepare('SELECT name, color, weight

FROM fruit

WHERE weight < ? AND color = ?');

$sth->bindValue(1, $weight, PDO::PARAM_INT);

$sth->bindValue(2, $color, PDO::PARAM_STR);

$sth->execute();

?>

<?php

function readData($dbh) {

$sql = 'SELECT name, color, weight FROM fruit';

try {

$stmt = $dbh->prepare($sql);

$stmt->execute();


/*  通过列号绑定  */

$stmt->bindColumn(1, $name);

$stmt->bindColumn(2, $color);

/*  通过列名绑定  */

$stmt->bindColumn('weight', $wgt);


while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {

$data = $name . "\t" . $color . "\t" . $wgt . "\n";

print $data;

}

}

catch (PDOException $e) {

print $e->getMessage();

}

}

readData($dbh);

?>








Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post