This question already has an answer here:
I'm stuck thinking of how I can avoid SQL injection attacks on my code.
This is what I have now.
<?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');
?>
How do I improve on this?
</div>
As suggested, prepared statements
are the best way to achieve good protection from SQL injection.
Shortened Example
You will need to add entries to fill in all columns you wish to insert.
$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" - represents the data type i.e "s" - string, "i" - integer for each entry.
values(?,?,?) - this is a placeholder for the bind_params statement so the '?' will be replaced in sequential order with the values you place in the bind_params method
$stmt->execute();
$_SESSION['notice'] = "Table updated";
}
else{
$_SESSION['notice'] = "Table could not be updated!";
}