I'm still trying to get my head around OO PHP. I haven't tackled it for a while, but I was just having a play around and finally managed to at least get something working. Is this a good way or a bad way to do it though? The idea is that I can run queries easier: index.php <?php require("class.php"); $fetchProperties = new StdClass; $fetchProperties->what = '*'; $fetchProperties->from = 'stories'; $fetchProperties->where = 'cat_id'; $fetchProperties->equals = 1; $do = new getStuff(); $do->getStories($fetchProperties); ?> PHP: classes.php class getStuff { public function getStories($fetchProperties){ if (isset($fetchProperties)){ include "" . $_SERVER['DOCUMENT_ROOT'] . "/_config/db.php"; $statement = $dbconn->prepare(" SELECT $fetchProperties->what FROM $fetchProperties->from WHERE $fetchProperties->where = :equals "); $statement->execute([ ":equals" => $fetchProperties->equals ]); $rows = $statement->fetchAll(PDO::FETCH_ASSOC); foreach ($rows AS $row){ var_dump($row); } }else { errorResponse("Must have all variables"); } } }//End getStuff PHP:
Nothing wrong with this. A few suggestions, though. Type hinting is excellent for this kind of things. getStories(stdClass $fetchProperties){ PHP: This makes sure you can't pass anything unexpected. Furthermore, I'd create a custom class for this. This way, you can pre-define the properties you want to have, and it gives you a little more control over it. class FetchProperties { public $what = ''; // etc... } PHP:
I am guessing you are planning on building that up, I would suggest you do it correctly the first time around. The following suggestions should get you established even for complex queries: 1) Make $what an array, this way you can add/remove elements from the what as you like. 2) Make the $where an array as well to give you the ability to have multiple conditions. 3) Escape all your arguments including the what and where. I assume the reason you did it because the source is trusted, nevertheless I would suggest you do. Finally (probably just thinking of other DB systems) you might want to separate the what, where, from into their own variables. getStories ($from, array $what = array('*'), array $where = array()); Code (markup):