What are some best practices for handling user input, such as names and emails, to prevent SQL injection attacks in PHP applications?

To prevent SQL injection attacks in PHP applications when handling user input, it is important to use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to separate the SQL logic from the user input, making it harder for attackers to inject malicious SQL code.

// Example of using prepared statements to handle user input for names and emails
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

$name = $_POST['name'];
$email = $_POST['email'];

$stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();