I'm writing this PHP function that sends a record to mySQL database. I heard that inserting variables into SQL statements can lead to SQL injection attacks. How can I fix my code to make it immune? My current code is:
<?php
$id= 1;
$message=json_decode(file_get_contents('php://input'),true)["message"];
$event="Message";
$servername = "localhost";
$username = "dev";
$password = "somepassword";
$dbname = "sampledatabase";
$dateModified = gmdate("Y-m-d h:i:s a");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die($conn -> connect_errno. " : ".$conn -> connect_error);
}
$sql = "INSERT INTO queries (ID, name, message, dateModified)
VALUES ('{$id}', '{$event}', '{$message}','{$dateModified}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully".$event;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
return $event;
?>
The message comes from a HTML form.
Also how do you hack this code to do something to this table? Say truncate?