How can PHP developers ensure data security and prevent SQL injection when dealing with user input in MySQL queries?

To ensure data security and prevent SQL injection when dealing with user input in MySQL queries, PHP developers should use prepared statements with parameterized queries. This approach separates SQL logic from user input, preventing malicious SQL code from being executed.

// Establish a connection to the MySQL 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 prepared statement
$stmt->bindParam(':username', $_POST['username']);

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

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