What are the best practices to prevent SQL injection when saving user inputs in a database using PHP?

SQL injection can be prevented by using prepared statements with parameterized queries in PHP. This technique ensures that user input is treated as data rather than executable code, thus preventing malicious SQL injection attacks.

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

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");

// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);

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