一个简单的例子:

php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
$hostname = "localhost"; //数据库地址
$dbuser = "root" //数据库 用户名
$dbpass = "toor"; //数据库密码
$dbname = "tgfs"; //数据库名

//设置一下用户名
$username = "Lixiney";
$password = "password";

//创建连接
$conn = new mysqli($hostname,$dbuser,$dbpass,$dbname);
if($conn -> connect_error){
die("数据库连接错误".$conn->connect_error);
} //地方数据库连接错误终止程序
$sql = "select * from user where username = ? and password = ?";
//定义查询语句 使用 ? 占位符
$stmt = $conn -> prepare($sql);
$stmt -> bind_param("ss",$username,$password); //绑定变量
$stmt -> execute();
$result = $stmt -> get_result(); //获取查询结果
$row = $result->fetch_assoc();
if($result -> num_rows > 0 and $row['password'] === $password){
echo "登录成功";
header("Location: vul/index.html");
}else{
echo "登录失败";
}

?>

预处理以及绑定变量

php
1
2
$result = $conn -> prepare("select * from user where username = ? and password = ?");
//使用 ? 当作占位符
php
1
$result -> bind_param("ss",$username$password);

第一个参数表示参数的类型

  • i 表示 整形
  • s 表示 字符串
  • d 表示 双精度浮点型
  • b 表示 二进制大对象

绑定输出结果的变量

php
1
$result->bind_result($name,$pwd);

执行查询

php
1
$result -> excute();

获取结果

php
1
$result = $stmt -> get_result();
php
1
$row = $result -> fetch_assoc();

关闭连接

php
1
2
$result -> close();
$conn -> close();