<body> <?php //.访问不同的数据库(举例) //造对象 $dsn = "mysql:dbname=test1;host=localhost"; $pdo = new PDO($dsn,"root","123"); //写sql语句 $sql = "update nation set name='兽族'where code='n002'"; //执行sql语句 $a = $pdo->exec($sql); //带上事务功能(举例中对于加入的东西其中一个与数据库重复,则都被回滚) //造对象 $dsn = "mysql:dbname=test1;host=localhost"; $pdo = new PDO($dsn,"root","123"); //设置异常模式 $pdo->setAttribute(pdo::ATTR_ERRMODE,pdo::ERRMODE_EXCEPTION);//(模式的名称 模式的值) //写sql语句 $sql1 = "insert into nation values('n005','精灵族') "; $sql2 = "insert into nation values('n006','人族') "; try { //启动事物 $pdo->beginTransaction(); $pdo->exec($sql1); $pdo->exec($sql2); //提交事务 $pdo->commit(); } catch(pdoexception $e)// pdo异常的一个类型 { //$e->getMessage(); //回滚 $pdo->rollBack(); } //另一个与catch相同的用法是final //防止sql注入(举例) //造对象 $dsn = "mysql:dbname=test1;host=localhost"; $pdo = new PDO($dsn,"root","123"); //写sql语句 $sqll = "insert into nation values(?,?)"; //准备sql语句,返回statement对象 $st = $pdo->prepare($sqll); //绑定参数 /*$st->bindparam(1,$code); $st->bindparam(2,$name); $code="n007"; $name="矮人族";*/ //或者用简单方法 $attr = array("n008","魔族"); //执行提交,不用给sql语句了,直接传过去了 //$st->execute(); $st->execute($attr); //预处理语句里面用?占位的,给数组的时候要给索引数组
//防止sql注入或者用name占用位置(举例)
//造对象 $dsn = "mysql:dbname=mydb;host=localhost"; $pdo = new PDO($dsn,"root","123"); //写SQL语句,预处理语句,使用name占位 $sql = "insert into nation values(:code,:name)"; //准备执行 $st = $pdo->prepare($sql); //绑定参数 /*$st->bindParam(":code",$code,PDO::PARAM_STR); $st->bindParam(":name",$name,PDO::PARAM_STR); $code="n024"; $name="狼族";*/ $attr = array("code"=>"n025","name"=>"虫族"); //执行 $st->execute($attr);
?> </body>