1 //PDO 2 //1.访问不同的数据库 3 //2.自带事务功能 4 //3.防止SQL注入 5 6 /*//1.造对象 7 $dsn = "mysql:dbname=mydb;host=localhost"; 8 $pdo = new PDO($dsn,"root","123"); 9 10 //2.写SQL语句 11 $sql = "update nation set name='兽族' where code='n013'"; 12 13 //3.执行SQL语句 14 //$r = $pdo->query($sql); 15 $r = $pdo->exec($sql);*/ 16 17 //事务功能 18 //造对象 19 $dsn = "mysql:dbname=mydb;host=localhost"; 20 $pdo = new PDO($dsn,"root","123"); 21 22 //设置异常模式 23 $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); 24 25 26 //写SQL语句 27 $sql1 = "insert into nation values('n016','人族')"; 28 $sql2 = "insert into nation values('n017','不死族')"; 29 30 //执行两条SQL语句 31 try 32 { 33 //启动事务 34 $pdo->beginTransaction(); 35 36 $pdo->exec($sql1); 37 $pdo->exec($sql2); 38 39 //提交事务 40 $pdo->commit(); 41 } 42 catch(PDOException $e) 43 { 44 //$e->getMessage(); 45 //回滚 46 $pdo->rollBack(); 47 }
1 //造对象 2 $dsn = "mysql:dbname=mydb;host=localhost"; 3 $pdo = new PDO($dsn,"root","123"); 4 5 //写SQL语句,预处理语句 6 $sql = "insert into nation values(?,?)"; 7 8 //准备SQL语句,返回statement对象 9 $st = $pdo->prepare($sql); 10 11 //绑定参数 12 /*$st->bindParam(1,$code); 13 $st->bindParam(2,$name); 14 15 $code="n022"; 16 $name="矮人族";*/ 17 18 $attr = array("n023","魔族"); 19 20 //提交执行,不用给SQL语句了,已经传过去了 21 var_dump($st->execute($attr)); 22 23 24 //预处理语句里面用?占位的,给数组的时候要给索引数组
1 //造对象 2 $dsn = "mysql:dbname=mydb;host=localhost"; 3 $pdo = new PDO($dsn,"root","123"); 4 5 //写SQL语句,预处理语句,使用name占位 6 $sql = "insert into nation values(:code,:name)"; 7 8 //准备执行 9 $st = $pdo->prepare($sql); 10 11 //绑定参数 12 /*$st->bindParam(":code",$code,PDO::PARAM_STR); 13 $st->bindParam(":name",$name,PDO::PARAM_STR); 14 15 $code="n024"; 16 $name="狼族";*/ 17 18 $attr = array("code"=>"n025","name"=>"虫族"); 19 20 //执行 21 $st->execute($attr);
1 //造对象 2 $dsn = "mysql:dbname=mydb;host=localhost"; 3 $pdo = new PDO($dsn,"root","123"); 4 5 //写SQL语句,预处理语句 6 $sql = "select * from nation"; 7 8 //准备执行 9 $st = $pdo->prepare($sql); 10 11 //执行 12 $st->execute(); 13 14 //读数据 15 var_dump($st->fetchAll(PDO::FETCH_ASSOC));
1 //写SQL语句,预处理语句,使用name占位 2 $sql = "insert into nation values(:code,:name)"; 3 4 //准备执行 5 $st = $pdo->prepare($sql); 6 7 //执行 8 $st->execute($_POST);