PHP造PDO对象和事务功能

时间:2023-12-11 17:45:44
<!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> //PDO
//数据访问抽象层
<?php //1.操作其它数据库
//2.事务功能
//3.防止SQL注入攻击 //造PDO对象
//$dsn = "mysql:dbname=mydb;host=localhost"; //数据源 ("数据库类型:数据库名称=名称;连接地址=什么什么;")
//$pdo = new PDO($dsn,"root","123"); 数据源,用户名,密码 //写SQL语句
//$sql = "select * from nation";
//$sql = "insert into nation values('n077','数据')"; //执行,返回的是PDOStatement对象
//$a = $pdo->query($sql); //执行查询
//$a = $pdo->exec($sql); //执行其他语句 //var_dump($a); //$arr = $attr->fetchAll(PDO::FETCH_BOTH);
//var_dump($arr); //事务功能
//事务:能够控制语句同时成功同时失败,失败时可以回滚 $dsn = "mysql:dbname=mydb;host=localhost";
$pdo = new PDO($dsn,"root","123"); //设置异常模式
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); try
{
//开启事务
$pdo ->beginTransaction(); $sql1 = "insert into nation values('n080','是删')";
$sql2 = "insert into nation values('n070','好几款')";
$sql3 = "insert into nation values('n075','好几款')"; $pdo->exec($sql1);
$pdo->exec($sql2);
$pdo->exec($sql3); //提交
$pdo->commit();
}
catch(Exception $e)
{
//抓住try里面出现的错误,并且处理
//echo $e->getMessage(); //获取异常信息 //回滚
$pdo->rollBack();
}
//final()
//{
//最终执行,无论以上try代码有没有出错,都会执行
//} ?> </body>
</html>