What is the difference between using fetch_array and fetch_object in PHP when retrieving data from a MySQL database?
When retrieving data from a MySQL database in PHP, the main difference between using fetch_array and fetch_object lies in the way the data is returned. fetch_array returns data as an associative array with both numeric and associative keys, while fetch_object returns data as an object with property names as column names. The choice between the two methods depends on how you want to access and manipulate the retrieved data in your PHP code.
// Using fetch_array to retrieve data from a MySQL database
$result = $mysqli->query("SELECT * FROM table");
while ($row = $result->fetch_array()) {
// Access data using both numeric and associative keys
echo $row['column_name'];
echo $row[0];
}
// Using fetch_object to retrieve data from a MySQL database
$result = $mysqli->query("SELECT * FROM table");
while ($row = $result->fetch_object()) {
// Access data using object properties
echo $row->column_name;
}
Keywords
Related Questions
- How can using code tags like [php]code[/php] improve the presentation of PHP code in online forums and discussions for better readability and understanding?
- How can PHP developers efficiently implement a "Read More" functionality that only appears when the content exceeds a certain length?
- What potential issues can arise with PHP sessions when using different browsers like Firefox and Internet Explorer?