What are common pitfalls when retrieving data from a MySQL database in PHP?

One common pitfall when retrieving data from a MySQL database 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. Another pitfall is not checking for errors when executing queries, which can result in unexpected behavior. Always check for errors after executing a query to ensure data retrieval was successful.

// Example of retrieving data from a MySQL database using prepared statements

// 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 SQL statement with a parameterized query
$stmt = $mysqli->prepare("SELECT column1, column2 FROM table WHERE id = ?");
$stmt->bind_param("i", $id);

// Set the parameter value and execute the query
$id = 1;
$stmt->execute();

// Check for errors
if ($stmt->error) {
    die("Query failed: " . $stmt->error);
}

// Bind the result variables and fetch the data
$stmt->bind_result($result1, $result2);
$stmt->fetch();

// Output the retrieved data
echo "Column 1: " . $result1 . "<br>";
echo "Column 2: " . $result2;

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