In what ways can SQL Injections be prevented when inserting data from $_POST directly into a MySQL query in PHP?

SQL Injections can be prevented by using prepared statements with parameterized queries in PHP when inserting data from $_POST directly into a MySQL query. This helps to separate the SQL logic from the data input, making it impossible for malicious SQL code to be injected into the query.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("INSERT INTO mytable (column1, column2) VALUES (:value1, :value2)");

// Bind the values from $_POST to the parameters in the query
$stmt->bindParam(':value1', $_POST['input1']);
$stmt->bindParam(':value2', $_POST['input2']);

// Execute the prepared statement
$stmt->execute();