Prevent SQL injections in PHP

If the user input is inserted unchecked into the SQL query, then the application becomes vulnerable to SQL injection attacks, as in the example below:

$variable = $_POST['input_utilisateur']; 

mysql_query("INSERT INTO 'table' ('column') VALUES ('$variable')");
In this example, the user can enter  value'); DROP TABLE table;--') . The query becomes:

mysql_query("INSERT INTO 'table' ('column') VALUES('value'); DROP TABLE table;--')

The hacker's goal is to modify the SQL query so that he can read hidden information or perform any other operation (read, modify, delete). In this example, the table is removed from the database.
This type of flaw is the most widespread and dangerous, and if your code is not secure, the risk would be enormous.

The solution to SQL injection flaws is to use prepared queries or parameterized queries. Preparing for execution, the query is sent to the database server and performs a syntax check. With this method, it is impossible for the hacker to inject malicious SQL.

For this, you have three options:

1- Using the PDO:

$statement = $pdo-> prepare('SELECT * FROM administrator WHERE name = :name'); 

$statement-> execute(array('name' => $nom));

foreach ($statement as $row) {
// do something
}
2- Using MySQLi:

$statement = $dbConnection-> prepare('SELECT * FROM administrator WHERE name = ?'); 
$statement-> bind_param('s', $nom);

$statement-> execute();

$result = $statement-> get_result();
while ($row = $result-> fetch_assoc()) {
// do something
}
3- Using the method PHP mysql_real_escape_string
PHP has its own method to fix this vulnerability, but it should be noted that the previous two methods are more effective. mysql_real_escape_string  takes a string that will be used in the MySQL query and returns the same string of characters escaped from any SQL injection. The quotas(') are replaced by \'. This function requires that you are already connected to the database to use it.

$nom = "' OR 1'"; 

$nom = mysql_real_escape_string($nom);

$query = "SELECT * FROM administrator WHERE name = '$nom'";
echo "Injection avoided: < br />" . $query . "< br />";

$name_vul = "'; DELETE FROM administrator WHERE 1 or name = '";

$name_vul = mysql_real_escape_string($name_vul);

$query_vul = "SELECT * FROM administrator WHERE name = '$nom'";
echo "Injection avoided: < br />" . $query_vul;

References:
https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php