PHPPDO的简单使⽤(query(),exec(),prepare(),Transact。。。
1 <html>
2 <body>
3 <?php
4#数据库连接
珠心算怎么学
5$dbtype = 'mysql';
6$host = 'localhost';
7$db = 'test';
8$ur = 'root';
9$psw = 'china0913';
10
11$dsn = $dbtype . ':host=' . $host . ';' . 'dbname=' . $db;
12
13try {
呼和浩特美食14$dbh = new PDO($dsn, $ur, $psw, array(PDO::ATTR_PERSISTENT=>true));
15echo '连接成功<br>';
16 } catch(Exception$e) {
17die('Connect Failed Message: ' . $e->getMessage());
赵贵诚18 }
19
20#使⽤query函数查询
21$sql = 'SELECT * FROM ur';
22$query = $dbh->query($sql);
23$query->tFetchMode(PDO::FETCH_ASSOC); //设置结果集返回格式,此处为关联数组,即不包含index下标
24$rs = $query->fetchAll();
25var_dump($rs);
26
27#使⽤exec函数进⾏INSERT,UPDATE,DELETE,结果返回受影响的⾏数
28$sql = 'INSERT INTO ur (`urName`, `urPassword`, `urAge`) SELECT (MAX(urId) + 1), \'123456\', 18 FROM ur'; //插⼊⼀⾏⽤户数据,其中urName使⽤urId最⼤值+1
29 // $rs = $dbh->exec($sql);
30 // var_dump($rs) . '<br>';
31
32#使⽤prepareStatement进⾏CURD
33$sql = 'SELECT * FROM ur WHERE urId = ?';
34$stmt = $dbh->prepare($sql);
35$stmt->bindParam(1, $urId); //绑定第⼀个参数值
坚持到底就是胜利
36$urId = 1;
37
38$stmt->execute();
39$stmt->tFetchMode(PDO::FETCH_ASSOC);
40$rs = $stmt->fetchAll();
41var_dump($rs);
42
43#使⽤事务
44try {
商议近义词
45$dbh->tAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //设置错误模式,发⽣错误时抛出异常
平开头的四字成语46$dbh->beginTransaction();
47$sql1 = 'SELECT bookNum FROM book WHERE bookId = ? FOR UPDATE'; //此处加上⾏锁,可以对bookNum做⼀些判断,bookNum>1,才做下⼀步更新操作
48$sql2 = 'UPDATE book SET bookNum=bookNum-1 WHERE bookId = ?'; //加上⾏锁后,如果ur1在买书,并且ur1的买书过程没有结束,ur2就不能执⾏SELECT查询书籍数量的操作,这样就保证了不会出现只有1本书,却两个⼈同时49$stmt1 = $dbh->prepare($sql1);
50$stmt2 = $dbh->prepare($sql2);
51$stmt1->bindParam(1, $urId);
52$stmt2->bindParam(1, $urId);
53$urId = 1;
54$stmt1->execute();
55$stmt2->execute();
酒能不能上高铁实践检验真理56$dbh->commit();
57 } catch(Exception$e) {
58$dbh->rollBack();
59die('Transaction Error Message: ' . $e->getMessage());
60 }
61 ?>
62 </body>
63 </html>