What potential pitfalls should be avoided when using MySQL queries in PHP?

One potential pitfall when using MySQL queries in PHP is the risk of SQL injection attacks if user input is not properly sanitized. To avoid this, always use prepared statements with parameterized queries to prevent malicious SQL code from being injected into your queries.

// 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 query with a placeholder for the user input
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

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

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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