mysqli参数化查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$mysqli = new mysqli("localhost", "root", "password", "test");

$author = $_GET['author'];

$query = "SELECT content FROM passage WHERE (author = ?)";

$stmt = $mysqli->stmt_init();

if ($stmt->prepare($query)) {
$stmt->bind_param("s", $author);
$stmt->execute();

$stmt->bind_result($content);
while ($stmt->fetch()) {
printf ("%s\n", $content);
}
$stmt->close();
}
$mysqli->close();

PDO参数化查询

安装和打开pdo:https://www.php.net/manual/zh/pdo.installation.php

1
2
3
4
5
6
7
8
$pdo = new PDO("mysql:host=localhost;dbname=test;charset=utf8", "root","password");
$statement = $pdo->prepare("select * from passage where author =?");
$author = $_GET['author'];
$statement->bindParam(1, $author);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
printf ("%s\n", $row["content"]);
}

mysql_real_escape_string

1
2
3
4
5
$username = $_GET['username'];
mysql_set_charset(GBK); //使用mysql_set_charset防御宽字符注入
$sql=sprintf("SELECT * FROM users WHERE username='%s'",mysql_real_escape_string($username);
mysql_query($query);
$result = mysql_query($sql);

这种方式虽然能够防御sql注入,但本质上仍是字符串拼接,不是真正的参数化查询