1. 数据库描述: 数据库名称: db_test 表名称: tb_user 表结构:
|      name      |       type        |    is null     |     is key        |       is auto       |
|----------------|-------------------|----------------|-------------------|---------------------|
|    id          |       int         |    not null    |    primary key    |    autoincrement    |
|    username    |    varchar(32)    |    not null    |    no primary key |    no auto increment|
|    password    |    varchar(64)    |    not null    |    no primary key |    no auto increment|

用户名: root            密码: root

  1. 连接数据库:
$mysqli = new mysqli($db_url, $db_user, $db_password, $db_name);
  1. 设定连接编码:
$mysqli->set_charset($db_charset);
  1. 判断是否连接正常:
if (mysqli_connect_errno()) {
    die('无法连接数据库: '.mysqli_connect_error());
}
  1. 获取预处理引用:
$sql_update = "UPDATE `tb_user` SET `password`=? where `username`=?";
$stmt = $mysqli->prepare($sql_update);
  1. 向预处理语句绑定数据:
$stmt->bind_param("ss", $password, $username);//i:integer;s:string;d:double;b:blob;
  1. 为变量设置真实数据:
$username = 'tom';//where username=$username
$password = 'apple';// set password=$password
  1. 执行预处理引用:
$stmt->execute();
  1. 检查是否正确执行:
$stmt_error = mysqli_stmt_error($stmt);
if (strlen($stmt_error) == 0) {
    echo('update successfully!');
} else {
    die('prepared statement ecexute error: '.$stmt_error);
}
  1. 关闭打开的数据库连接:
$stmt->close();
$mysqli->close();

完整的代码如下:

$mysqli = new mysqli('localhost', 'root', 'root', 'db_test');
$mysqli->set_charset('utf8');
if (mysqli_connect_errno()) {
    die('无法连接数据库: '.mysqli_connect_error());
}

$sql_update = "UPDATE `tb_user` SET `password`=? WHERE `username`=?";
$stmt = $mysqli->prepare($sql_update);

$stmt->bind_param("ss", $password, $username);//i:integer;s:string;d:double;b:blob;

$username = 'tom';//WHERE username=$username
$password = 'banana';//SET password=$password

$stmt->execute();

$stmt_error = mysqli_stmt_error($stmt);
if (strlen($stmt_error) == 0) {
    echo('update successfully!');
} else {
    die('prepared statement ecexute error: '.$stmt_error);
}

$stmt->close();
$mysqli->close();