Correction status:Uncorrected
Teacher's comments:
效果图:
处理操作是通过一个叫预处理对象的工具来操作的: 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');