PHP中的PDO预处理机制

具体代码如下,PDO预处理机制主要用于数据库交互。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
/**
* Create By Da4er.
*/
//使用pdo连接数据库
$dsn = "mysql:host=127.0.0.1;port=3306;dbname=pikachu;charset=utf8";
$username = "root";
$pasword ="123";
$PDOObject =new PDO($dsn, $username, $pasword);
var_dump($PDOObject);
//对象常用方法
//exec()函数 执行sql语句,返回影响的行数
//$sql = "insert into users(id,username,password) values (null,'admin','345')";
//$count = $PDOObject->exec($sql);
//echo "影响的行数为:{$count}";
//query()函数,执行一个sql语句 返回一个结果集
//$sql = "select * from users";
//$result = $PDOObject->query($sql);
//var_dump($result);
//lastInsertId() 返回最后插入行的id或序列值(string类型)
//$sql = "insert into users(id,username,password) values (null,'admin','345')";
//$count = $PDOObject->exec($sql);
//echo "影响的行数为:{$count}";
//$id = $PDOObject->lastInsertId();
//echo $id;
//setAttribute()设置pdo的一些通用属性 看手册
//PDOStatement对象常用方法
// fetch()从结果集中获取一行,并向下移动指针
$sql = "select * from users";
//$result = $PDOObject->query($sql);
//while($arr=$result->fetch(PDO::FETCH_ASSOC)){
// print_r($arr);
//}
//fetchALL()返回一个包含结果集中所有行的数组
$result = $PDOObject->query($sql);
$arr = $result->fetchAll(PDO::FETCH_ASSOC);
//foreach ($arr as $key=>$value){
// foreach ($value as $key2=>$value2){
// echo $key2."=>".$value2."\r\n";
// }
//}
//rowCount()返回影响行数
$count = $result->rowCount();
echo $count;
//PDO预处理 important
//使用问号占位符
$sql = "insert into users(id,username,password) values (?,?,?)";
$result = $PDOObject->prepare($sql);
$result->bindValue(1,12);
$result->bindValue(2,"da4er");
$result->bindValue(3,"qweasdzxc");
$result->execute();
//使用值占位符
$sql = "insert into users(id,username,password) values (:id,:username,:password)";
$result = $PDOObject->prepare($sql);
$result->bindValue(":id",13);
$result->bindValue(":username","admin888");
$result->bindValue(":password","888");
$result->execute();
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×