r/PHPhelp • • Jan 18 '11

Getting into OO PHP coding (I've been doing things procedurally) -- question about displaying results from a database and/or populating an object.

7 Upvotes

I ask because I am unsure how people do this. Displaying results (for a simple page) procedurally from a database is rather simple. It goes like this:

$conn = mysql_connect(blah blah);
mysql_select_db($dbname);

Important part: $query = "SELECT * FROM Table1 WHERE ID = 1111"; $thing = mysql_query($query); list($result1, $result2, ..., $result20) = mysql_fetch_row($thing);

Then later on, you simply insert the items like this:

<h3><?php echo $result1 ?></h3>

<p><?php echo $result2 ?></p>

etc.

Whereas, with OO code would it be something like (assuming similar object properties for database fields, and I would also prepare the statements, but for the sake of verbosity not here): (?)

<?php
class Hrm
{
    public $result1;
    public $result2;
    ...
    public $result20;
}

$dbh = new PDO(blah blah);
$query = "SELECT * FROM Table1 WHERE ID = 1111";
$res = $dbh->query($query);
$resulting_object = $res->fetchALL(PDO::FETCH_CLASS, 'Hrm');
?>

eventually to be used as:

<h3><?php echo $resulting_object->result1 ?></h3>

<p><?php echo $resulting_object->result2 ?></p>


  1. Is this right?

  2. Is it more common to generate an anonymous object (FETCH_OBJ) or key-values (FETCH_ASSOC) if we are just displaying data with nothing fancy going on? I'm guessing the major benefit to using a pre-structured class would be to access already built methods to easily manipulate the data -- right?

  3. If we wish to populate a pre-structured class, what if your object properties don't align with your database fields, and how then do you populate a pre-structured object's properties?

My apologies in advance if these are pedantic questions.