Blogger Information
Blog 31
fans 0
comment 1
visits 24727
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用预处理实现更新与删除操作20180424
jobing的博客
Original
900 people have browsed it

今天学习了使用MySQLi面向过程,使用预处理技术来实现对数据库的操作,以下是相关的使用预处理更新与删除操作代码,与大家分享:

更新代码:

实现了将名为郭靖的工资更新为9999

实例

<?php 
//1.连接数据库
require 'mysqli_connect.php';

//2.准备SQL语句
$sql = 'UPDATE staff SET salary=? WHERE name=?;';

//3.创建stmt对象
$stmt = mysqli_stmt_init($db);

//4.检测SQL语句
if (mysqli_stmt_prepare($stmt, $sql)) {

    /* 参数绑定 */
    mysqli_stmt_bind_param($stmt, "is", $salary,$name);
    $salary = 9999;
    $name = '郭靖';

    /* 执行SQL语句 */
    mysqli_stmt_execute($stmt);
    echo '<br>更新了'.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 staff  WHERE name=?';

//3.创建stmt对象
$stmt = mysqli_stmt_init($db);

//4.检测SQL语句
if (mysqli_stmt_prepare($stmt, $sql)) {

    /* 参数绑定 */
    mysqli_stmt_bind_param($stmt, "s", $name);
    $name = '周芷若';

    /* 执行SQL语句 */
    mysqli_stmt_execute($stmt);
    echo '<br>删除了'.mysqli_stmt_affected_rows($stmt).'条记录';

} else {
    exit(mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt));
}
/* 注销stmt对象 */
mysqli_stmt_close($stmt);

/* 关闭数据库连接 */
mysqli_close($db);

运行实例 »

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

效果图:

更新操作

111.png111-1.png111-2.png111-3.png

删除操作

555.png555-1.png555-2.png555-3.png


总结:

操作步骤

1.连接数据库

2.准备SQL语句

3.创建stmt对象:mysqli_stmt_init($db)

4.检测SQL语句:

其中参数绑定使用函数mysqli_stmt_bind_param($stmt, "s", $name);

执行SQL语句使用函数mysqli_stmt_execute($stmt))

5.注销stmt对象:mysqli_stmt_close($stmt)

6.关闭数据库连接:mysqli_close($db)

Correction status:qualified

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