How can PHP developers prevent SQL injection when using databases for user management?

To prevent SQL injection when using databases for user management, PHP developers should use prepared statements with parameterized queries. This approach ensures that user input is properly escaped and sanitized before being executed as a SQL query, reducing the risk of malicious SQL injection attacks.

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

// Prepare a SQL statement with placeholders for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');

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

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

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