user3268379
user3268379

Reputation: 141

PHP Returning array of objects from rows

I want the php to be able to load all the rows in the table into an object each and then add them all to an array and return the array to be converted into java objects etc.

<?php


ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

$dbhost     = "localhost";
$dbname     = "Example";
$dbuser     = "Example";
$dbpass     = "Example";

 $conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$objectArray = array();

$stmt = $conn->prepare("SELECT * FROM Table");
while ($row = $stmt->fetch()) 
  {
    #add all columns on this row to an object and add to array
  }
$stmt->execute();

if(!$stmt)
    print_r($dbh->errorInfo());

?>

Upvotes: 0

Views: 65

Answers (2)

Cups
Cups

Reputation: 6896

You can also fetch results into a defined class.

Read this reply: PDO PHP Fetch Class

Upvotes: 0

Ron van der Heijden
Ron van der Heijden

Reputation: 15080

Why not using the PDO::FETCH_OBJ

$array = array();
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) 
{
    #add all columns on this row to an object and add to array
    $array[] = $row; // $row is an object now
}

Upvotes: 1

Related Questions