mysqli的预处理操作
实例
<?php $host = "localhost"; $user="abc"; $pwd="abc"; $db="test"; //连接数据库 $conn = new mysqli($host,$user,$pwd,$db); //设定传输字符集 $conn->set_charset('utf8'); //检测是否连接成功 !$conn->connect_error or die("数据库连接出错"); //先查看数据库中有多少条数据 $sql = "select count(*) from user"; $stmt = $conn->prepare($sql); $stmt->execute(); $stmt->bind_result($count); while($stmt->fetch()){ echo $count; } //插入一些数据,构建sql语句 $sql="INSERT INTO `user` (name,pwd) VALUES (?,?)"; //创建预处理对象 $stmt = $conn->prepare($sql); //占位符变量 $name = "小红"; $pwd = "aabbcc"; //填充占位符 $stmt->bind_param("ss",$name,$pwd); //执行sql插入 $res = $stmt->execute(); if($res){ echo "<br>插入一条数据;"; }else{ echo "<br>数据插入失败"; } //修改数据 $sql = "UPDATE `user` SET `name`=?,`pwd`=? where `name`=?"; $stmt=$conn->prepare($sql); $name="小光"; $pwd="123321"; $where="小红"; $stmt->bind_param("sss",$name,$pwd,$where); if($stmt->execute()){ echo "修改成功"; }; //查看修改的数据 $sql = "SELECT `pwd` FROM `user` WHERE `name`=?"; $stmt = $conn->prepare($sql); $name = '小光'; $stmt->bind_param('s',$name); $stmt->execute(); $stmt->bind_result($pwd); while ($stmt->fetch()) { echo "<br>".$pwd; } //删除小光的记录 $sql = "DELETE FROM `user` WHERE `name` = ?"; $stmt = $conn->prepare($sql); $name = '小光'; $stmt->bind_param('s',$name); if($stmt->execute()){ echo "记录为小光的删除成功"; } ?>
运行实例 »点击 "运行实例" 按钮查看在线实例
pdo的优势:pdo是php和各种sql的中间件,使用pdo的话就不用考虑对面是哪种数据库了。
编程作业:
实例
<?php //pdo连接数据库 $dsn = "mysql:host=localhost;dbname=test"; $user = "abc"; $pwd = "abc"; try{ $pdo = new PDO($dsn,$user,$pwd); }catch(PDOException $e){ echo $e->getMessage(); } //设定pdo的传输字符编码 $pdo->query('set names utf8'); //先插入一点数据 $sql = "INSERT IGNORE INTO `t` (name,age) values (:name,:age)"; //创建pdo预处理对象 $stmt = $pdo->prepare($sql); //占位符数据 //插入一些实验数据 $data=['name'=>'小明','age'=>13]; $stmt->execute($data); for ($i=0; $i <5; $i++) { $data=['name'=>'路人'.$i,'age'=>$i*6]; if (!$stmt->execute($data)) { echo "操作出错"; break; } } //现在查询数据库中有几条数据 $sql = "SELECT count(*) FROM `t`"; $stmt= $pdo->prepare($sql); $stmt->execute(); echo "<br>现在有".$stmt->fetchColumn()."条数据"; //现在将小明的年龄改成24岁 $sql = "UPDATE `t` SET `age`=:age WHERE `name`=:where"; $stmt = $pdo->prepare($sql); $data=['age'=>24,'where'=>'小明']; if($stmt->execute($data)){ echo "<br>修改成功"; }else{ echo "<br>修改失败"; } //现在来查看小明的年龄是多少 $sql = "SELECT `age` FROM `t` WHERE `name`=:where"; $stmt = $pdo->prepare($sql); unset($data); $data['where']= '小明'; $stmt->execute($data); while ($res = $stmt->fetch(PDO::FETCH_ASSOC)) { echo "小明的年龄是",$res['age'],"岁<br>"; } //现在需要删除年龄是24岁的用户 $sql = "DELETE FROM `t` WHERE `age`=:where"; $stmt = $pdo->prepare($sql); $data=['where'=>24]; if($stmt->execute($data)){ echo "<br>删除24岁的用户成功<br>"; } //再次查看数据库中有哪些用户 $sql ="SELECT * FROM `t`"; $stmt= $pdo->prepare($sql); $stmt->execute(); //将结果集绑定到变量中,遍历输出 $stmt->bindColumn('id',$id); $stmt->bindColumn('name',$name); $stmt->bindColumn('age',$age); while ($stmt->fetch()) { echo "<br>id为",$id,"的用户是",$name,"年龄为",$age; } ?>
运行实例 »
点击 "运行实例" 按钮查看在线实例