How can I prevent SQL syntax error when typing quotes, and prevent injection attacks as well?

Viewed 24

enter image description here

How can I make this code better, so that it wouldn't be as vulnerable to an SQL injection, and will allow the use of quotes in the input?

1 Answers

You should try to convert your code into below prepared statement code it will help to prevent from injections. You can also see the following link. https://www.w3schools.com/php/php_mysql_prepared_statements.asp

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) 
VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
Related