//PDO:数据访问抽象层
//dsn:数据源:
//带有事务功能:
$dsn = "mysql:host=localhost;dbname=mydb";
//造pdo对象
$pdo = new PDO($dsn,"root","123");
//设置为异常模式
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION );
try
{
//写SQL语句
$sql = "insert into Nation values('n009','藏族')";
$sql1 = "insert into Nation values('n001','藏族')";
//$sql2 = "insert into Nation values('n012','藏族')";
//启动事务
$pdo->beginTransaction();
//执行SQL语句
$pdo->exec($sql);
$pdo->exec($sql1);
//$pdo->exec($sql2);
$pdo->commit();
}
catch(PDOException $e)
{
//echo $e->getMessage();
//回滚事务
$pdo->rollBack();
}
/*foreach($a as $v)
{
var_dump($v);
}*/
第二特点:可以防止SQL注入攻击
<?php //2.可以防止SQL注入攻击 $dsn="mysql:host=localhost;dbname=mydb"; $pdo = new PDO($dsn,"root","123"); $sql = "insert into Nation values(?,?)"; //将一条SQL语句放到服务器等待执行 $stm = $pdo->prepare($sql); /*//绑定参数 $stm->bindParam(1,$code); $stm->bindParam(2,$name); //给变量赋值 $code = "n030"; $name = "哈空间";*/ $attr = array("n031","客户"); //执行预处理语句,执行成功返回true,执行失败返回false if($stm->execute($attr)) { //var_dump($stm->fetch()); //var_dump($stm->fetchAll(PDO::FETCH_ASSOC)); } ?>