Blogger Information
Blog 55
fans 0
comment 1
visits 42110
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用预处理技术实现更新与删除操作(4-24)-2018年5月1日18点0分
旺小舞的博客
Original
616 people have browsed it

效果图:

4-24.jpg


处理操作是通过一个叫预处理对象的工具来操作的: STMT

基本步骤:

1.创建stmt预处理对象

2.检测SQL语句

3.参数绑定

4.执行查询

5.注销stmt预处理对象

6.关闭数据库连接

mysql_pre_query.php 代码:

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

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

//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).'条记录,主键是:'.mysqli_stmt_insert_id($stmt);

    //再次添加新数据,只需要给新变量并执行一下就可以了
    // $staff_id = 7;

    /* 执行SQL语句 */
    // mysqli_stmt_execute($stmt);
    // echo '<br>更新了'.mysqli_stmt_affected_rows($stmt).'条记录,主键是:'.mysqli_stmt_insert_id($stmt);

    // $name = '武大郎';

    /* 执行SQL语句 */
    // mysqli_stmt_execute($stmt);
    // echo '<br>新增了'.mysqli_stmt_affected_rows($stmt).'条记录,主键是:'.mysqli_stmt_insert_id($stmt);



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

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

运行实例 »

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

mysqli_connect.php

<?php 
header("Content-type:text/html;charset=utf-8");
/**
 * 创建数据库连接
 */
//1,创建连接参数
// define('DB_HOST', '127.0.0.1');
// define('DB_USER', 'root');
// define('DB_PASS', 'root');
// define('DB_NAME', 'php');
// define('DB_CHAR', 'utf-8');
require 'mysqli_config.php';
//2,调用连接函数返回连接对象 
$db = mysqli_connect(DB_HOST,DB_USER,DB_PASS);
//3,判断是否连接成功
if(mysqli_connect_errno($db)){
	exit('连接失败'.mysqli_connect_error($db));
}
// echo '<h1>连接成功</h1>';
//4,选择默认数据库
mysqli_select_db($db,DB_NAME);
//5,设置客户端默认字符编码集
mysqli_set_charset($db,DB_CHAR);

mysqli_config.php

<?php 
//1,创建连接参数
define('DB_HOST', '127.0.0.1');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_NAME', 'php');
define('DB_CHAR', 'utf-8');



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