码迷,mamicode.com
首页 > Web开发 > 详细

php PDO:数据访问抽象层

时间:2016-06-20 20:28:32      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
<!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>
View Code
技术分享
<!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>
View Code
技术分享
<!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>
View Code

 

php PDO:数据访问抽象层

标签:

原文地址:http://www.cnblogs.com/bilibiliganbei/p/5601656.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!