//PDO:数据访问抽象层 $dsn = "mysql:dbname=mydb;host=localhost";//造PDO对象 $pdo = new PDO($dsn,"root","123"); //写SQL语句 $sql = "select * from bookname_w"; $stm = $pdo->query($sql);//执行SQL查询语句,返回PDOSTATEMENT对象 $sql = "update bookname_w set bookname='php1' where id=o"; $arr = $pdo->exec($sql);//执行SQL增删改语句 //读数据 $arr = $stm->fetch(PDO::FETCH_NUM); $arr = $stm->fetchAll(PDO::FETCH_ASSOC); var_dump($arr);
//事务功能 同时修改,有错误都不做修改 $dsn = "mysql:dbname=mydb;host=localhost"; $pdo = new PDO($dsn,"root","123"); //把PDO的错误模式设置为异常模式 $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); //捕获异常 try { //开启事务功能 $pdo->beginTransaction(); $sql1 = "insert into bookname_w values('','css')"; $sql2 = "insert into bookname_w values('','dw')"; $sql3 = "insert into bookname_w values('','java')"; $pdo->exec($sql1); $pdo->exec($sql2); $pdo->exec($sql3); //提交事务 $pdo->commit(); } catch(Exception $e) { //捕获异常并解决异常 //回滚 $pdo->rollBack(); //var_dump($e); }