What potential pitfalls can occur when fetching data from a MySQL database in PHP?

One potential pitfall when fetching 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 to securely fetch data from the database.

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

// Prepare a statement
$stmt = $mysqli->prepare("SELECT * FROM table WHERE id = ?");

// Bind parameters
$stmt->bind_param("i", $id);

// Set the parameter
$id = 1;

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

// Bind the result
$stmt->bind_result($result);

// Fetch the data
$stmt->fetch();

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

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