What potential pitfalls should be considered when using MySQL queries in PHP, based on the code snippet shared?

One potential pitfall when using MySQL queries in PHP is the risk of SQL injection attacks if user input is not properly sanitized. To prevent this, it is recommended to use prepared statements with parameterized queries to safely handle user input.

// Example of using prepared statements to prevent SQL injection

// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Prepare a statement with a placeholder for the user input
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind the user input to the statement
$stmt->bind_param("s", $username);

// Set the user input
$username = $_POST['username'];

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

// Get the result set
$result = $stmt->get_result();

// Fetch the data
while ($row = $result->fetch_assoc()) {
    // Process the data
}

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