What is the difference between accessing data from fetch() as an array and as an object in PHP?
When accessing data from fetch() as an array in PHP, you can easily loop through the data using foreach to access each item. On the other hand, accessing data as an object allows you to access properties using arrow notation. To access data as an object, you need to use the fetch(PDO::FETCH_OBJ) method when fetching data from a database query in PHP.
// Accessing data from fetch() as an array
$stmt = $pdo->query('SELECT * FROM table');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
echo $row['column_name'] . "<br>";
}
// Accessing data from fetch() as an object
$stmt = $pdo->query('SELECT * FROM table');
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $row) {
echo $row->column_name . "<br>";
}
Keywords
Related Questions
- How can PHP be used to handle multilingual content in database queries and sorting?
- Are there best practices for handling JSON data in PHP, especially when it comes to updating specific values within the JSON structure?
- What alternative approach is suggested in the forum thread to handle multiple values from checkboxes in PHP?