What are some best practices for handling MySQL queries in PHP to avoid common pitfalls like SQL injection vulnerabilities?

One common pitfall in handling MySQL queries in PHP is SQL injection vulnerabilities, where malicious users can manipulate input to execute unauthorized SQL commands. To avoid this, always use parameterized queries with prepared statements to sanitize user input and prevent SQL injection attacks.

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Sanitize user input and execute the query
$username = $_POST['username'];
$stmt->execute();

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

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