实例 MySQLi面向对象实现更新操作
<?php //1.连接数据库 require 'mysqli_connect.php'; //2.准备SQL语句 $sql = "UPDATE user SET name=? WHERE id=?;"; //3.创建STMT预处理对象 $stmt = $mysqli->stmt_init(); //4.检测预处理SQL语 if ($stmt->prepare($sql)) { //绑定参数到预处理SQL语句 $stmt->bind_param('si',$name,$id); //设置参数 $name = '杨过'; $id = 4; //执行预处理语句 $stmt->execute(); if ($stmt->affected_rows > 0 ){ echo '<br>成功更新'.$stmt->affected_rows.'条记录'; } else { echo '<br>没有更新记录'; } //5.注销stmt对象 $stmt->close(); } else { exit($stmt->errno.':'.$stmt->error); } //6. 关闭数据库连接 $mysqli->close();
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例 PDO实现删除操作
<?php $pdo = new PDO('mysql:dbname=php','root','root'); $sql = "DELETE FROM `user` WHERE id=:id;"; $stmt = $pdo->prepare($sql); //$data = ['name'=>'杨过','sex'=>'男','age'=>'25']; $id = 4; $stmt->bindParam(':id',$id,PDO::PARAM_STR); if($stmt->execute()){ //rowCount():返回上一个SQL语句影响的行数 echo '<h3>成功删除了'.$stmt->rowCount().'条记录</h3>'; }else{ echo '<h3>删除失败</h3>'; print_r($stmt->errorInfo()); exit(); } //销毁PDO对象 $pdo = null; /** * Created by PhpStorm. * User: Administrator * Date: 2018/5/1 0001 * Time: 20:1 */
运行实例 »
点击 "运行实例" 按钮查看在线实例