在PHP中,使用PDO(PHP Data Objects)擴展時,可以使用預處理語句和參數綁定來防止SQL注入攻擊。以下是使用參數綁定的方法:
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_db";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 設置 PDO 錯誤模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "連接失敗: " . $e->getMessage();
}
$stmt = $conn->prepare("INSERT INTO your_table (column1, column2) VALUES (:value1, :value2)");
在這個例子中,:value1
和 :value2
是參數占位符。
$value1 = "value1_data";
$value2 = "value2_data";
// 綁定參數到占位符
$stmt->bindParam(':value1', $value1, PDO::PARAM_STR);
$stmt->bindParam(':value2', $value2, PDO::PARAM_STR);
在這個例子中,我們將參數$value1
和$value2
綁定到對應的占位符。PDO::PARAM_STR
指定了參數的數據類型為字符串。
try {
$stmt->execute();
echo "新記錄插入成功";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
將以上代碼整合在一起,完整的示例如下:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_db";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// 設置 PDO 錯誤模式為異常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO your_table (column1, column2) VALUES (:value1, :value2)");
$value1 = "value1_data";
$value2 = "value2_data";
// 綁定參數到占位符
$stmt->bindParam(':value1', $value1, PDO::PARAM_STR);
$stmt->bindParam(':value2', $value2, PDO::PARAM_STR);
$stmt->execute();
echo "新記錄插入成功";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// 關閉連接
$conn = null;
?>