What are the best practices for handling user input to prevent SQL injection attacks in PHP?

SQL injection attacks occur when malicious users input SQL queries into a form field, which can manipulate the database and potentially gain unauthorized access to sensitive information. To prevent SQL injection attacks in PHP, it is important to sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries, which separate the SQL logic from the user input.

// Establish database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Sanitize and validate user input
$user_input = $_POST['user_input'];
$user_input = $conn->real_escape_string($user_input);

// Prepare and execute SQL query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user_input);
$stmt->execute();

// Process results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process each row
}

// Close statement and connection
$stmt->close();
$conn->close();