What are common mistakes to avoid when handling MySQL queries in PHP?

One common mistake to avoid when handling MySQL queries in PHP is not properly escaping user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely pass user input to the database.

// Incorrect way without prepared statements
$user_input = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$user_input'";
$result = mysqli_query($connection, $query);

// Correct way using prepared statements
$user_input = $_POST['username'];
$query = "SELECT * FROM users WHERE username = ?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "s", $user_input);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);