我一直在思考如何避免对我的代码进行SQL注入攻击。
这就是我现在所拥有的。
<?php
session_start();
$email = $_POST['e-mail'];
$fn = $_POST['firstname'];
$ln = $_POST['lastname'];
$cp = $_POST['cellphone'];
$phn = $_POST['phone_number'];
$comp = $_POST['company'];
$prov = $_POST['province'];
$brgy = $_POST['barangay'];
$fadd = $_POST['address'];
$sadd = $_POST['address2'];
$conn = mysqli_connect('localhost','root','','newcartdb')or die('Could not connect');
foreach($_POST['product'] as $product)
{
$date = date('Y-m-d H:i:s');
$order_name = $product['item_name'];
$order_code = $product['item_code'];
$order_qty = $product['item_qty'];
$sub_total = $product['price'];
$query = "INSERT INTO `newcartdb`.`orders`(`Email`,`Firstname`,`Lastname`,`ContactNum`,`PhoneNum`,`Company`,`Province`,`Barangay`,`FAddress`,`SAddress`,`ProductName`,`ProductCode`,`Qty`,`SubTotal`,`datetime`) VALUES('$email','$fn','$ln','$cp','$phn','$comp','$prov','$brgy','$fadd','$sadd','$order_name','$order_code','$order_qty','$sub_total','$date')";
mysqli_query($conn,$query);
}
mysqli_close($conn);
header('Location: order_confirmation.php');
?>
我如何改进?
答案 0 :(得分:0)
根据建议,prepared statements
是从SQL注入中获得良好保护的最佳方式。
缩短示例
您需要添加条目以填写要插入的所有列。
$email = $_POST['e-mail'];
$fn = $_POST['firstname'];
$ln = $_POST['lastname'];
if ($stmt = $mysqli->prepare("INSERT INTO `newcartdb`.`orders`(Email,Firstname,Lastname) values(?,?,?)) {
$stmt->bind_param("sss", $email, $fn, $ln);
“sss” - 表示数据类型,即“s” - 字符串,“i” - 每个条目的整数。
values(?,?,?) - 这是bind_params语句的占位符,所以'?'将使用您在bind_params方法
中放置的值按顺序替换 $stmt->execute();
$_SESSION['notice'] = "Table updated";
}
else{
$_SESSION['notice'] = "Table could not be updated!";
}