What are potential pitfalls when using mysqli to retrieve data from a database in PHP?

One potential pitfall when using mysqli to retrieve data from a database in PHP is not properly handling errors that may occur during the query execution. To solve this issue, always check for errors after executing a query using mysqli_error() or mysqli_errno() functions.

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

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

// Execute a query
$result = $mysqli->query("SELECT * FROM table");

// Check for errors
if (!$result) {
    die("Error: " . $mysqli->error);
}

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

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