What are some best practices for securely handling form input variables in PHP to prevent SQL injection?

To prevent SQL injection in PHP, it is essential to sanitize and validate all form input variables before using them in SQL queries. One best practice is to use prepared statements with parameterized queries to separate SQL logic from user input. Additionally, using functions like mysqli_real_escape_string() or PDO::quote() can help sanitize input data.

// Example of using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Sanitize and validate user input
$username = $_POST['username'];

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

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

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