Blogger Information
Blog 64
fans 2
comment 1
visits 46852
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用预处理技术实现更新与删除操作——2018年4月24日
Y的博客
Original
583 people have browsed it

删除操作:

实例

<?php
//预处理删除操作
//1.连接数据库
require 'connect.php';
//2.准备SQL语句,将变量部分使用占位符进行代替
$sql = "DELETE FROM staff WHERE  id=?";
$id=4;
//3.创建并初始化预处理对象stmt
$stmt = mysqli_stmt_init($db);
//4.用stmt对象检测预处理语句是否正确,成功返回true,错误返回false
if(mysqli_stmt_prepare($stmt,$sql)){
    /* 将变量与SQL语句中的占位符进行绑定 */
    mysqli_stmt_bind_param($stmt,"i",$id);
    /* 执行SQL语句 */
    if(mysqli_stmt_execute($stmt)){
        //判断是否执行成功:受影响的记录数量
        if(mysqli_stmt_affected_rows($stmt)>0){
            echo '删除成功,主键是:'.mysqli_stmt_insert_id($id);
        }else{
            echo '没有删除数据';
        }
    }else{//返回SQL执行阶段的错误
        exit(mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt));
    }
}else{
    //返回SQL检测阶段的错误
    exit(mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt));
}
/* 注销stmt对象 */
mysqli_stmt_close($stmt);
/* 关闭数据库连接 */
mysqli_close($db);

运行实例 »

点击 "运行实例" 按钮查看在线实例

更新操作:

实例

<?php
//预处理更新操作
//1.连接数据库
require 'connect.php';
//2.准备SQL语句,将变量部分使用占位符进行代替
$sql = "UPDATE staff SET age=? WHERE id=?";
$age=30;
$id=3;
//3.创建并初始化预处理对象stmt
$stmt = mysqli_stmt_init($db);
//4.用stmt对象检测预处理语句是否正确,成功返回true,错误返回false
if(mysqli_stmt_prepare($stmt,$sql)){
    /* 将变量与SQL语句中的占位符进行绑定 */
    mysqli_stmt_bind_param($stmt,"ii",$age,$id);
    /* 执行SQL语句 */
    if(mysqli_stmt_execute($stmt)){
        //判断是否执行成功:受影响的记录数量
        if(mysqli_stmt_affected_rows($stmt)>0){
            echo '更新成功,主键是:'.mysqli_stmt_insert_id($stmt);
        }else{
            echo '没有更新数据';
        }
    }else{//返回SQL执行阶段的错误
        exit(mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt));
    }
}else{
    //返回SQL检测阶段的错误
    exit(mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt));
}
/* 注销stmt对象 */
mysqli_stmt_close($stmt);
/* 关闭数据库连接 */
mysqli_close($db);

运行实例 »

点击 "运行实例" 按钮查看在线实例

手抄:

1.jpg

总结:

基本步骤:
* 1.创建stmt预处理对象:$stmt = mysqli_stmt_init($db)
* 2.检测SQL语句:if(mysqli_stmt_prepare($stmt,$sql))
* 3.参数绑定:mysqli_stmt_bind_param($stmt, "siii", $name,$sex,$age,$salary);
* 4.执行查询if: (mysqli_stmt_execute($stmt))
* 5.注销stmt预处理对象:mysqli_stmt_close($stmt);
* 6.关闭数据库连接:mysqli_close($db);

Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post