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

One common 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");

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

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

// Set parameters and execute
$id = 1;
$stmt->execute();

// Bind result variables
$stmt->bind_result($col1, $col2);

// Fetch results
while ($stmt->fetch()) {
    echo "Column 1: $col1, Column 2: $col2";
}

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