How can the fetch_array function in PHP be optimized to retrieve multiple rows of data from a MySQL database efficiently?
When using the fetch_array function in PHP to retrieve multiple rows of data from a MySQL database, it is important to optimize the process for efficiency. One way to do this is by using a loop to fetch each row of data one at a time, rather than fetching all rows at once. This can help reduce memory usage and improve performance when dealing with a large dataset.
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve data from the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Fetch and display each row of data
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
// Process the data here
echo $row['column_name'] . "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
Related questions
-
PHP code quality maintainability
-
PHP database data output
-
PHP installer script user input