NEKO

php使用参数化查询

2018/02/11

参数化sql查询可以防止sql注入

参数化sql查询可以防止sql注入的关键在于预编译机制,这样转入的值只是被数据库当做参数来处理,并不会当做语句。

在php中使用参数化查询

旧的 mysql 扩展不支持参数化查询,mysqli 和 PDO 这两个新扩展都支持参数化查询。

mysqli

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$mysqli = new mysqli("localhost","dbusername", "dbpassword", "database");  

$username= "somename";
$password= "someword";

$query = "SELECT filename, filesize FROM users WHERE (name = ?) and (password = ?)";

$stmt = $mysqli->stmt_init();

if ($stmt->prepare($query)) {
$stmt->bind_param("ss",$username, $password);
$stmt->execute();

$stmt->bind_result($filename,$filesize);
while($stmt->fetch()) {
printf ("%s : %d\n",$filename, $filesize);
}
$stmt->close();
}

$mysqli->close();

PDO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

$pdo = new PDO("mysql:host=localhost;dbname=database","dbusername", "dbpassword");

$username= "somename";
$password= "someword";

$query = "SELECT * FROM users WHERE (name = :username) and (password = :password)";

$statement= $pdo->prepare($query,array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$statement->bindParam(":username",$username, PDO::PARAM_STR, 10);
$statement->bindParam(":password",$password, PDO::PARAM_STR, 12);
$statement->execute();

while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
printf ("%s : %d\n",$row["filename"],$row["filesize"]);
}
$statement->closeCursor();

$pdo = null;

原文作者: n3k0

发表日期: February 11th 2018, 1:17:44

发出嘶吼: 没有魔夜2玩我要死了

CATALOG
  1. 1. 参数化sql查询可以防止sql注入
  2. 2. 在php中使用参数化查询
    1. 2.1. mysqli
    2. 2.2. PDO