要防止SQL注入攻击,可以使用参数化查询或转义输入数据。
使用参数化查询:
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 准备查询语句
$stmt = $conn->prepare("SELECT * FROM users WHERE username=? AND password=?");
$stmt->bind_param("ss", $username, $password);
// 设置参数并执行查询
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->execute();
// 获取结果
$result = $stmt->get_result();
$rows = $result->fetch_all(MYSQLI_ASSOC);
// 处理结果
foreach($rows as $row){
echo $row['username'] . " " . $row['password'];
}
// 关闭连接
$stmt->close();
$conn->close();
使用mysqli_real_escape_string转义输入数据:
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 转义输入数据
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// 执行查询
$result = mysqli_query($conn, "SELECT * FROM users WHERE username='$username' AND password='$password'");
// 处理结果
while($row = mysqli_fetch_assoc($result)){
echo $row['username'] . " " . $row['password'];
}
// 关闭连接
mysqli_close($conn);
无论哪种方法,都需要确保用户输入数据经过适当的处理,以防止恶意SQL注入攻击。