0

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?

Shri
  • 709
  • 1
  • 7
  • 23
  • 1
    Your code is extremely vulnerable to SQL injection. You can pass any values and then your code will display the full error message. This way an attacker can get all of the data from your database very easily. – Dharman Dec 24 '19 at 10:24
  • SQL injection isn't always malicious. It can simply be a mistake that results in an error unnecessarily. For example, test what happens if you input a `message` that contains an apostrophe character. It doesn't damage your database, but it won't insert correctly. Using query parameters fixes this. There are examples in the post linked as a duplicate, or in this manual page: https://www.php.net/manual/en/mysqli-stmt.bind-param.php – Bill Karwin Dec 24 '19 at 17:44

0 Answers0