How can PHP developers prevent SQL injection attacks when handling user registration and login processes?

To prevent SQL injection attacks in PHP when handling user registration and login processes, developers should use prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps sanitize user input and prevents malicious SQL code from being executed.

// Using prepared statements to prevent SQL injection in user registration process

// Assuming $conn is the database connection object

$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $password);

// Set parameters and execute
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->execute();
$stmt->close();