一、预处理实现更新操作
<?php //1.连接数据库 require 'mysqli_connect.php'; //2.准备SQL语句 $sql = "UPDATE user SET email=? WHERE user_name=?"; //3.创建stmt对象 $stmt = mysqli_stmt_init($db); //4.检测SQL语句 if(mysqli_stmt_prepare($stmt,$sql)){ //参数绑定 mysqli_stmt_bind_param($stmt,'ss',$email,$username); $email = 'peter@php.cn'; $username = 'peter'; //执行SQL语句 mysqli_stmt_execute($stmt); echo '更新了'.mysqli_stmt_affected_rows($stmt).'条记录'; }else{ exit(mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt)); } //注销stmt对象 mysqli_stmt_close($stmt); //关闭数据库连接 mysqli_close($db);
运行结果:
二、预处理实现删除操作
<?php //1.连接数据库 require 'mysqli_connect.php'; //2.准备SQL语句 $sql = "DELETE FROM user WHERE user_id=?"; //3.创建stmt对象 $stmt = mysqli_stmt_init($db); //4.检测SQL语句 if(mysqli_stmt_prepare($stmt,$sql)){ //参数绑定 mysqli_stmt_bind_param($stmt,'i',$id); $id = 2; //执行SQL语句 mysqli_stmt_execute($stmt); echo '删除了'.mysqli_stmt_affected_rows($stmt).'条记录'; }else{ exit(mysqli_stmt_errno($stmt)).':'.mysqli_stmt_error($stmt); } //注销stmt对象 mysqli_stmt_close($stmt); //关闭数据库连接 mysqli_close($db);
运行结果: