Jay Gould Jay Gould - 8 days ago 5
PHP Question

Deserializing SQL table to object collection

I'm trying to deserialize an SQL table to a collection of objects in PHP and I'm lost as to how I can do so.

In C#, the equivalent would be:

public class Object
{
public string objectProperty { get; set; }
public string anotherProperty { get; set; }
}

public void Deserialize()
{
List<Object> collection = new List<Object>();

// Assuming that we have an SQL statement returning a row

foreach (Row row in returnedSqlRow)
{
collection.Add(new Object
{
objectProperty = row["objectProperty"],
anotherProperty = row["anotherProperty"]
});
}
}


which would give me a nice collection of
Objects
to work with.

In my PHP I have the following:

class Book {
public $CN; // cataloguenumber
public $title;
public $author;
public $description;
public $price;
public $enteredby;
}


with my SQL statement being:

$books = pg_query($conn, 'SELECT cataloguenumber, title, author, description, price, enteredby FROM CSBooks');


I can easily access each value from the row like so:

while($row = pg_fetch_row($books)) {

echo $row[0] . '<br>';
echo $row[1] . '<br>';
echo $row[2] . '<br>';
echo $row[3] . '<br>';
echo $row[4] . '<br>';
echo $row[5] . '<br>';
}


But I'm lost as to how I can create an object collection and deserialize the row to a
Book
object and store it. Is there a PHP equivalent? I've taken a look at
pg_fetch_object()
but it doesn't quite seem to be what I'm looking for.

Answer

I think the solution is to use PDO and PDOStatement::fetchObject which will abstract all the pg_* functions and make your db interaction easier to manage.

It will return a stdObject instead of an array by default, but you can make it map your object.

There would be a dirty solution if you really need to use pg_* functions instead of PDO... (I am ashamed to suggest it)

$a = ['a'=>'bla', 'b'=>1];
$shame = (object) $a;

Then on your class, you just write a constructor to bind the columns to the object fields...