PDO:数据访问抽象层

时间:2022-03-11 02:29:03
<?php
//PDO:数据访问抽象层
//带有事务功能;
//dsn:数据源
$dsn="mysql:host=localhost;dbname=aaas";
//造pdo对象
$pdo=new PDO($dsn,"root","");//数据源,用户名,密码
//启动事务
$pdo->beginTransaction();
//写SQL语句
$sql="select * form Info"; //执行SQL语句
$a=$pdo->query($sql); //回滚事务
//$pdo->RollBack(); foreach($a as $v)
{
var_dump($v);
} ?> <?php

  特点二:

<!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
//可以防止SQL注入攻击
$dsn="mysql:host=localhost;dbname=aaas";
$pdo=new PDO($dsn,"root","");
$sql="select * from Nation";
//将一条SQL语句放在服务器上准备运行
$stm=$pdo->prepare($sql);
//执行预处理语句,执行成功返回true,失败返回false
if($stm->execute())
{
var_dump($stm->fetch());
}
?> <?php
//可以防止SQL注入攻击
$dsn="mysql:host=localhost;dbname=aaas";
$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="壮族"; //执行预处理语句,执行成功返回true,失败返回false
if($stm->execute());
{
var_dump($stm->fetch());
} ?> <?php
//可以防止SQL注入攻击
$dsn="mysql:host=localhost;dbname=aaas";
$pdo=new PDO($dsn,"root",""); $sql="insert into Nation values(?,?)";
//将一条SQL语句放在服务器上准备运行
$stm=$pdo->prepare($sql); $attr=array("n005","苗族"); //执行预处理语句,执行成功返回true,失败返回false
if($stm->execute($attr));
{ }
?> <?php
//可以防止SQL注入攻击
$dsn="mysql:host=localhost;dbname=aaas";
$pdo=new PDO($dsn,"root",""); $sql="insert into Nation values(:code,:name)"; //将一条SQL语句放在服务器上准备运行
$stm=$pdo->prepare($sql); $attr=array("code"=>"n007","name"=>"水族"); //执行预处理语句,执行成功返回true,失败返回false
if($stm->execute($attr));
{ }
?> </body>
</html>