What is the best way to prevent SQL injection in PHP

I am working on a PHP application which contains various forms like signup, signin, product entries, etc which contains many input field. I know that SQL injection is a common attack which can be used to manipulate database tables records and also get sensitive data from database

Is there any way that we can use to prevent these attacks on the application after deployed on server.

1 Answers

Use PDO statements for databases of any type that you are connecting through database drivers. If you are using PDO Prepared Statement then it will be quite impossible to execute SQL injection attack on your server. A simple PHP code where we have used PDO statements and executed queries is as below 

<?php
    $host = "localhost";
    $username = "root";
    $password = "password";
    $db = "MyDatabase";

    $conn = new PDO("mysql:host=$host;dbname=$db", $username, $password);

    $statement = $conn->prepare("INSERT INTO Students (firstname, lastname, email)
    VALUES (:firstname, :lastname, :email)");

    $statement->bindParam(':firstname', $firstname);
    $statement->bindParam(':lastname', $lastname);
    $statement->bindParam(':email', $email);

    //ADD A ROW
    $firstname = "Rax";
    $lastname = "Pro";
    $email = "[email protected]";
    $statement->execute();
?>

If you are using MySQLi to connect to the MYSQL database, you can use real escape string function to escape characters that are used for SQL injection attack. Also, convert HTML special characters to prevent from XSS attack. A simple code to encode HTML special characters and adding escapes from posted string is as below

<?php
    $fullname = trim($_POST['fullname']);
    $fullname = htmlspecialchars($fullname);
    $fullname = $conn->real_escape_string($fullname);

?>
Ask question now
Never leave your website again in search of code snippets by installing our chrome extension.