php PDO:数据访问抽象层

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head> <body>
<?php //PDO:数据访问抽象层
//dsn:数据源
//1.带有事务功能:
$dsn="mysql:host=localhost;dbname=bilibili";
//造PDO对象
$pdo=new PDO($dsn,"root",""); //设置为异常模式
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION ); try
{
//写SQL语句
$sql="insert into nation values ('n007','白族')";
$sql1="insert into nation values ('n002','白族')";
//$sql2="insert into nation values ('n008','白族')"; //启动事务
$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);
}
*/ ?>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head> <body>
<?php //2.防止SQL注入攻击
$dsn="mysql:host=localhost;dbname=bilibili";
$pdo=new PDO($dsn,"root",""); $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));
} ?>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head> <body>
<?php //2.防止SQL注入攻击
$dsn="mysql:host=localhost;dbname=bilibili";
$pdo=new PDO($dsn,"root",""); $sql="insert into nation values(:code,:name)"; //将一条SQL语句放到服务器等待执行
$stm=$pdo->prepare($sql); /*//绑定参数
$stm->bindParam(1,$code);
$stm->bindParam(2,$name); //给变量赋值
$code="n030";
$name="蒙古";*/ $attr=array("code"=>"n032","name"=>"土家"); //执行预处理语句,执行成功返回true,执行失败返回false
if($stm->execute($attr))
{
//var_dump($stm->fetch());
//var_dump($stm->fetchAll(PDO::FETCH_ASSOC));
} ?>
</body>
</html>
上一篇:为红米Note 5 Pro编译Lineage OS 15.1的各种坑


下一篇:PDO数据访问抽象层