您的位置 >>> 星想互联 >>> 编程技术 >>> PHP基础
PDO和PDO预处理方法实例
点击数:4997  发布时间2017-09-17 01:44:56

<?php
header("Content-type: text/html; charset=gb2312");
 $host='localhost';
 $user ='root';
 $pwd='';
 $dbname='news';
 $msci='gb2312';

$mypdo=new PDO("mysql:host=$host;dbname=$dbname","$user","");
$mypdo->query("set names gb2312");

$sql="seleck * from news limit 0,5";
 $stmt=$mypdo->query($sql);

 foreach($stmt as $v){
 echo $v['title'];
 }
echo "<br>";

$stmk=$mypdo->prepare($sql);
$stmk->execute();

foreach($stmk as $v){
 echo $v['title'];
 }

//PDO预处理,参数占位符
$sql="inserts into news(title,author,content) values(:title,:author,:content)";
$stmt=$mypdo->prepare($sql);

$datas=array(
 array('title'=>'PHP1','author'=>'xn','content'=>'PHP',),
 array('title'=>'PHP2','author'=>'xn','content'=>'PHP',),
 array('title'=>'PHP3','author'=>'xn','content'=>'PHP',),
 array('title'=>'PHP4','author'=>'xn','content'=>'PHP',),
 array('title'=>'PHP5','author'=>'xn','content'=>'PHP',),
);

foreach($datas as $row){
   $stmt->execute($row);
}

//PDO预处理,?号占位符
$sql="inserts into news(title,author,content) values(?,?,?)";
$stmt=$mypdo->prepare($sql);

$datas=array(
 array('PHPA','xn','PHP',),
 array('PHPB','xn','PHP',),
 array('PHPC','xn','PHP',),
 array('PHPD','xn','PHP',),
 array('PHPE','xn','PHP',),
);

foreach($datas as $row){
   $stmt->execute($row);
   var_dump($row)  ;
}

$sql="selects * from news";
$stmt=$mypdo->prepare($sql);
$stmt->execute();
echo $stmt->rowcount();
?>

来源:咸宁网站建设