我通常会手动设置sqli参数检查(即检查输入是否是有效的电子邮件)。
虽然在这种情况下,我需要将用户消息放入我的数据库
这将如何运作?
我尝试了这段代码,但整个输入都以某种方式被删除了。
<?php
$text = "Hello World";
echo "$text is now ";
$text = stripslashes($text);
$text = mysqli_real_escape_string($text);
echo $text;
?>
谢谢你!
答案 0 :(得分:0)
防止在PHP中注入SQL:
您可以使用以下任何方式实现此目的:
对于MySQLi(MySQL):
$stmt = $dbConnection->prepare('SELECT id, username, email_id FROM users WHERE type = ?');
$stmt->bind_param('s', $userType); // bind parameters
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
注意:对于MySQLi,可以使用程序样式或Object oriented style(推荐)
对于PDO(PDO是任何受支持的数据库驱动程序的通用解决方案):
$stmt = $this->db->prepare('SELECT id, username, email_id FROM users WHERE type =:user_type');
$stmt->bindValue(':user_type', $userType);
$stmt->execute();
$user_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($user_list as $key => $list) {
echo '<a href="'. $list['id'].'">' . $list['email_id']. '</a></br>';
}
PDO连接
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from users') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
为您提供mysqli
的链接参数
$text = $db->mysqli_real_escape_string($text);
示例:强>
//Escaping characters
$db->real_escape_string('This is an unescaped "string"');
//There is an alias function that you can use which is shorter and less to type:
$db->escape_string('This is an unescape "string"');