<?php
//预处理操作
try {
$pdo=new PDO("mysql:host=localhost;dbname=xsphpdb", "root", "123456");
}catch(PDOException $e){
echo $e->getMessage();
}
/* pdo中有两种占位符号
*
* ? 参数 --- 索引数组, 按索引顺序使用
* 名子参数 ----关联数组, 按名称使用,和顺序无关
*/
$stmt=$pdo->prepare("insert into shops(name, price, num, desn) values(?, ?, ?, ?)"); //所有SQL都可执行
//准备好了一条语句,并入到服务器端,也已经编译过来了,就差为它分配数据过来
//$stmt=$pdo->prepare("insert into shops(name, price, num, desn) values(:name,:price, :num, :desn)");
$stmt=$pdo->prepare("update shops set name =:name,num=:num,price=:price where id=:id");
//绑定名称参数
/*
$stmt->bindParam(":name", $name);
$stmt->bindParam(":num", $num);
$stmt->bindParam(":desn", $desn);
$stmt->bindParam(":price", $p);
*/
//绑定问号参数,都可以加类型,不提供自动转类型
$stmt->bindParam(1, $name, PDO::PARAM_STR);
$stmt->bindParam(3, $num, PDO::PARAM_INT);
$stmt->bindParam(4, $desn, PDO::PARAM_STR);
$stmt->bindParam(2, $p, PDO::PARAM_STR);
$name="wwww1";
$num=101;
$desn="hello1";
$p=34.51;
if($stmt->execute()){
echo "执行成功";
echo "最后插入的ID:".$pdo->lastInsertId();
}else{
echo "执行失败!";
}
$name="ooo";
$num=101;
$desn="hello1";
$p=34.51;
if($stmt->execute()){
echo "执行成功";
echo "最后插入的ID:".$pdo->lastInsertId();
}else{
echo "执行失败!";
}
执行过程中绑定参数的形式,问号参数采用索引数组,名字参数采用关联数组
$stmt=$pdo->prepare("insert into shops(name, price, num, desn) values(:name,:price, :num, :desn)");
$stmt->execute(array(":price"=>99, ":name"=>"kkk1", ":num"=>"451", ":desn"=>"aaaaaa1"));
$stmt->execute(array(":price"=>88, ":name"=>"kkk2", ":num"=>"452", ":desn"=>"aaaaaa2"));
$stmt->execute(array(":price"=>77, ":name"=>"kkk3", ":num"=>"453", ":desn"=>"aaaaaa3"));
获取结果
<?php
try {
$pdo=new PDO("mysql:host=localhost;dbname=xsphpdb", "root", "123456");
}catch(PDOException $e){
echo $e->getMessage();
}
//获取结果 fetch() fetchAll();
$stmt=$pdo->prepare("select id, name, price, num, desn from shops where id > :id order by id");
$stmt->execute(array(":id"=>100));
$stmt->setFetchMode(PDO::FETCH_ASSOC);//设置获取数组的模式,关联数组
/*
while($row=$stmt->fetch()){
print_r($row);
echo '<br>';
}
*/
$data=$stmt->fetchAll();//获取整个表数据
echo '<pre>';
print_r($data);
echo '</pre>';
绑定列的方式获取数据
$stmt=$pdo->prepare("select id, name, price, num, desn from shops where id > :id order by id");
$stmt->bindColumn("id", $id, PDO::PARAM_INT);
$stmt->bindColumn("price", $price);
$stmt->bindColumn("name", $name, PDO::PARAM_STR);
$stmt->bindColumn(4, $num);
$stmt->bindColumn(5, $desn);
$stmt->execute(array(":id"=>100));
echo '<table border=1 width=900 align="center">';
echo '<tr>';
for($i=0; $i<$stmt->columnCount(); $i++){
$field=$stmt->getColumnMeta($i);//获取列名
echo '<th>'.$field["name"]."</th>";
}
echo '</tr>';
while($stmt->fetch()){
echo '<tr>';
echo '<td>'.$id.'</td>';
echo '<td>'.$name.'</td>';
echo '<td>'.$price.'</td>';
echo '<td>'.$num.'</td>';
echo '<td>'.$desn.'</td>';
echo '</tr>';
}
echo '</table>';
echo "总记录数:".$stmt->rowCount()."<br>";
echo "总字段数:".$stmt->columnCount()."<br>";