Are there any best practices recommended for preventing SQL injection in PHP?

SQL injection can be prevented in PHP by using prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to separate SQL code from user input, making it impossible for malicious SQL code to be injected into the query.

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the parameter in the query
$stmt->bindParam(':username', $_POST['username']);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();