要防止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注入攻擊。