r/PHPhelp • u/[deleted] • 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.
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>
Is this right?
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?
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.
2
Jan 19 '11
DB objects are always one of the first things people attempt when venturing into oop
Fill out this template
class DB{
public function __construct($host, $user, $pass, $database){}
private function _connect(){}
public function runQuery($quey){}
}usage would look someting like this
$db = new DB(//credentials);
$results = $db->runQuery("select * from table");
foreach($results as $set){
//do something with set
}
2
u/maskapony Jan 18 '11
Normally I'd pull all of the associative values (FETCH_ASSOC) into a class variable array called $row.
Then use function __get($attribute) { return $this->row[$attribute] }
in the class to dynamically access the results from the database. Here's an example interface that would be good to aim for.