PDO:: 数据访问抽象层 ? :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <?php //定义数据源 $dsn="mysql:dbname=test2;host=localhost"; //$dsn="sqlsrv:dbname"; //造pdo对象 $pdo=new PDO($dsn,"root","123"); //写SQL语句 $sql="select * from Info"; //准备执行语句 $st=$pdo->prepare($sql); //执行预处理语句 $st->execute();// 条件判断 返回true 或 false if ($st->execute()) { print_r($st->fetch()); //一次调用一条 } else{ echo "执行失败!"; } //从结果集中取所有数据,返回二维数组 //print_r($st->fetchAll(PDO::FETCH_NUM)); //从结果集中取一条数据中的某一列,返回字符串 //var_dump($st->fetchColumn(1)); //从结果集中取一条数据,返回一个实体类的对象 //var_dump($st->fetchObject()); ?> </body> </html>
② ????? prepare($sql) bindParam(1,$XX) $XX="ss" exectue() 方式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <?php //造PDO对象 $pdo=new PDO("mysql:dbname=test2;host=localhost","root","123"); //写SQl语句 $sql="insert into Info values(?,?,?,?,?)"; //准备SQL语句 $st=$pdo->prepare($sql); //给SQL语句分配变量 $st->bindParam(1,$code); $st->bindParam(2,$name); $st->bindParam(3,$sex); $st->bindParam(4,$nation); $st->bindParam(5,$birthday); //给变量赋值 $code="p120"; $name="回家"; $sex=true; $nation="n002"; $birthday="1988-9-6"; //执行SQL语句 $st->execute(); ?> </body> </html>
????? prepare($sql) exectue(array("ss")) 方式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <?php //造PDO对象 $pdo=new PDO("mysql:dbname=test2;host=localhost","root","123"); //写SQl语句 $sql="insert into Info values(?,?,?,?,?)"; //准备SQL语句 $st=$pdo->prepare($sql); $st->execute(array('p0030','克隆',true,'n001','1989-2-3'));//把分配变量和赋值干掉,只用这句。 ?> </body> </html>
③::::: prepare($sql) bindParam("",$XX,PDO::PARAM_STR); $XX="" exectue() 方式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <?php //造PDO对象 $pdo=new PDO("mysql:dbname=test2;host=localhost","root","123"); //写SQl语句 $sql="insert into info values(:c,:n,:s,:na,:b)"; //准备SQL语句 $st=$pdo->prepare($sql); //绑定参数 $st->bindParam("c",$code,PDO::PARAM_STR); $st->bindParam("n",$name,PDO::PARAM_STR); $st->bindParam("s",$sex,PDO::PARAM_STR); $st->bindParam("na",$nation,PDO::PARAM_STR); $st->bindParam("b",$birthday,PDO::PARAM_STR); //参数赋值 $code="p181"; $name="纳"; $sex=true; $nation="n002"; $birthday="1988-2-3"; //执行 $st->execute(); ?> </body> </html>
::::: prepare($sql) execute(); 方式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <?php //造PDO对象 $pdo=new PDO("mysql:dbname=test2;host=localhost","root","123"); //写SQl语句 $sql="insert into info values(:c,:n,:s,:na,:b)"; //准备SQL语句 $st=$pdo->prepare($sql); $st->execute(array('c'=>'p190','n'=>'水果','s'=>true,'na'=>'n002','b'=>'1990-2-3')); ?> </body> </html>