What are common pitfalls when executing MySQL queries in PHP?

One common pitfall when executing MySQL queries in PHP is not properly sanitizing 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. Additionally, make sure to handle errors properly to avoid potential issues with query execution.

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

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

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

$username = $_POST['username']; // assuming this is user input
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    // do something with the data
}

$stmt->close();
$mysqli->close();