PHP - Srp With A "crate" Object
Suppose I am coding up a crating calculator. A crate is a box with dimensions, weight, built of certain material, and having certain contents.
The crating calculator I am writing is one that computes dimensions of the box, once given dimensions of variou contents put into it.
Right now I have a factory that figures out which contents object to create, in order to figure out contents dimensions.
Something like
class CrateDimensionFactory { function getDimensionAwareClass(array $options) { return $dimensionAwareObject; } } //later in some code: $dimensionAwareObject->getDimensions();Now, I want to also put in the weight of crate which is the sum of contents of crate plus the weight of the crate. Question ... do I stick the weight computations into the same factory? i.e. class CrateFactory { function getDimensionAwareClass(array $options) { return $dimensionAwareObject; } function getWeightAwareClass(array $options) { return $weightAwareObject; } } //later in some code: $dimensionAwareObject= (new CrateFactory())->getDimensionAwareClass($options); $dimensionAwareObject->getDimensions(); $weightAwareObject= (new CrateFactory())->getWeightAwareClass($options); $weightAwareObject->getWeight();I can even stick the weight into the same returned object, where I create a single object from Factory, and then just call $crateAwareObject= (new CrateFactory())->getCrateAwareClass($options); $crateAwareObject->getDimensions(); $crateAwareObject->getWeight();There are many ways to do it .. I guess. But the spirit of my question is -- should I, do I put dimensions and weights together or separately, and how exactly do I separate them or how exactly do I put them together, with regards to how SRP is concerned? Similar TutorialsHey all, I want to have an object that has a property which is an object containing instances of other objects. I try this: Code: [Select] class Blog extends Posts { public $has_posts; public function __construct($a,$b,$c){ $has_posts = (object) array_merge((array) $a, (array) $b, (array) $c); } } class Posts { public $b; public function __construct($b){ $this->b = $b; } } $post1 = new Posts(1); $post2 = new Posts(2); $post3 = new Posts(3); $blog = new Blog($post1,$post2,$post3); var_dump($blog->has_posts); //null foreach($blog->has_posts as $post){ //Invalid argument supplied for foreach() echo $post->b; } But as you see, has_posts is null, not an object containing other objects. Thanks for response. I have a Soup object in a Bowl object in a Microwave object. The Microwave object has the methods: receiveItem(Bowl $b) cookItem(???) I want the Microwave to be able to set the Soup->temperature but I'm not how to do that? Make sense? TomTees I made a small script and it says that my database object isn't an object. I connect to my pdo database via: <?php try { $db = new PDO("mysql:host=localhost;dbname=database", "root", "root"); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo $e->getMessage(); } ?> The error I get is Code: [Select] Notice: Undefined variable: db in /Users/JPFoster/Sites/jobiji_sandbox/extensions/tasks.php on line 21 Fatal error: Call to a member function query() on a non-object in /Users/JPFoster/Sites/jobiji_sandbox/extensions/tasks.php on line 21 here's where the error is $grabber = $db->query('SELECT * WHERE user_id =' . $userid); $grabber->setFetchMode(PDO::FETCH_OBJ); while ( $row = $grabber->fetch() ){ $display = '<div>Task Name: ' . $row->name .'</div>'; $display .= '<div>Task Details: <p>'. $row->details .'</p></div>'; //$display .= '<div>'. $this->checkifDone($row->task_status) .'</div>'; $display .= '<div>Task Due: '. $row->task_due . '</div>'; echo $display; } could anyone tell me where this issue is originating I followed a fairly simple tutorial that didn't seem to work. Thanks! Ok. So, I'm trying to retrieve the id value from an object. Here is the code I have that works so far: Code: [Select] $object = 'object'; $koid = $this->$object; echo '<pre>'; print_r($koid); echo '</pre>'; and this is what is returns: Code: [Select] Order Object ( [id:protected] => 5 [stand_by:protected] => test [problem:protected] => test ) what do I need to do to make $koid equal the id value (5 in this case)? Hi I have a login script which goes at the top of several pages in my site. It works fine but I am trying to save some coding and re-writing out my script at the top of each of the pages. Instead I have made a page called login.php and put all of the code for the script in there. Looks like this.... <?php //login script if(isset($_POST['log'])) { $emaillog = stripslashes($_POST['emaillog']); $passwordlog = stripslashes($_POST['passwordlog']); $emaillog = mysql_real_escape_string($_POST['emaillog']); $passwordmd5 = md5($passwordlog); //generate random session id which i want to follow the user round the site! $CheckUser = "SELECT * FROM members WHERE email='".$emaillog."' AND password='".$passwordmd5."'"; $userDetails2 = mysql_query($CheckUser); $userInfo = mysql_fetch_array($userDetails2); $count = mysql_num_rows($userDetails2); if($count != 0) { $_SESSION['memberID'] = $userInfo['memberID']; $_SESSION['accesslevel']= $userInfo['accesslevel']; $_SESSION['email']= $userInfo['email']; //add an id that will be carried throughout the user until the session is destroyed function getUniqueCode2($length2 = "") { $code2 = md5(uniqid(rand(), true)); if ($length2 != "") return substr($code2, 0, $length2); else return $code2; } $randomKey = getUniqueCode2(25); $_SESSION['key'] = $randomKey; //the user must have an access level of 2, before they can login if($_SESSION['accesslevel']=='2') $url = "loggedin/index.php"; header("Location: ".$url.""); $success = '1'; } else { $success = '0'; $logged = "incorrect login details" or die(mysql_error()); } //now we need to update the login table to reflect a login if($success =='1'){ $time = date("Y-m-d h:m:s"); $qupdate_mem_logins = "INSERT INTO logindetails (`email`,`time`) VALUES ('".$emaillog."','".$time."')"; $rupdate_mem_logs = mysql_query($qupdate_mem_logins) or die(mysql_error()); ?> Now on the index page how do I reffer to this login script when someone fills in the form At the minute I have the following code but it is not checking or running anything. <?php //login script if(isset($_POST['log'])) { include('login.php'); } } ?> I am trying to get elements in a dom object to display and manipulate however i cant seem to get them all out: This is the feed: <TransactionList> <TransactionID>507821041</TransactionID> <TransactionDate>2012-03-12T13:23:00+00:00</TransactionDate> <MerchantID>547</MerchantID> <MerchantName>The High Street Web</MerchantName> <ProgrammeID>1865</ProgrammeID> <ProgrammeName>THE HIGHSTREET WEB</ProgrammeName> <TrackingReference>{CLICKID}</TrackingReference> <IPAddress>82.34.245.167 </IPAddress> <SaleValue>0.0000</SaleValue> <SaleCommission>0.0400</SaleCommission> <LeadCommission>0.0000</LeadCommission> </TransactionList> However i am trying to get more than 1 tag but i cant seem to get it right. This is my code: <?php $dom = new DomDocument; $dom -> load ( "http://xyz.com" ); $tracking = $dom -> getElementsByTagName( "TrackingReference" ); //$com = $dom -> getElementsByTagName( "SaleCommission" ); $c1 = 0; foreach( $tracking as $code ) { #echo $code -> textContent.'<br>'; $tcode = $code -> textContent; $tcom = $com -> textContent; //$com = $dom -> getElementsByTagName( "SaleCommission" ); if ($tcode !="") { $remove_it = '{CLICKID}'; $tcode = str_replace($remove_it, "", $tcode); echo $tcode.' VALUE '. $com .'<br>'; $c1 ++; } } echo 'Total Count: '.$c1; ?> Please can someone help and tell me where im going wrong! I've been trying to solve this issue for so long now.. I believe I'm close, but it's just the last part that I can't figure out how to solve.. I have a set of parsers and a controller. each parser is in it's own object named like Parsers_Imdb_Imdb.. What I want now is to be able to do this Code: [Select] $parse = new Parsers; $imdb = $parse->Imdb->get_info('some random info'); So far I've managed to get into the Imdb parser object, but I 'm not able to grab the method. parsers.php Code: [Select] class Parsers { function __construct() { } public function Imdb() { new Parsers_Imdb_Imdb; } } imdb.php Code: [Select] class Parsers_Imdb_Imdb extends Parsers { function __construct() { parent::__construct(); } public function get_info() { echo "get_info()"; } } I've got a __autoload() to solve the class declaration.. Could anyone please help me out with this? Thanks in advance hello all, I am new to php, and getting better using the object oriented approach. I have been a procedural programmer for several years, with a limited exposure to OOP. I have a question about pulling two values from an object. the following code is an excerpt from a class form. function getstocklist($currentcount){ $transactions = $currentcount['count']; $current = mysql_query("SELECT * FROM current_positions WHERE positiontype = 'long' OR positiontype = 'short'"); $tickers = ''; while ($stock = mysql_fetch_array($current)){ $tickers .= $stock['positionticker'] . ','; $stockList[] = array( 'shares' => round(($stock['positioncost']/$stock['positionprice']),0), 'date' => date("m/d/Y G:i:s", $stock['positiontime']-(45*60)), 'ticker' => $stock['positionticker'], 'type' => $stock['positiontype'], 'price' => $stock['positionprice'], ); } return($tickers); } I would like to get both the value of $tickers and the array $stockList. I am not sure how to proceed. any suggestions would be greatly appreciated. Thanks Kansas ok that works fine can i store a object tag in the db and show that same obj tag in the div ill paste my code but its hard coded <div id="resultmedia"> <object width="640" height="385"> <param name="movie" value="http://www.youtube.com/v/vFagaB9M6nQ?fs=1&hl=en_GB"></param> <param name="allowFullScreen" value="true"></param> <param name="allowscriptaccess" value="always"></param> <embed src="http://www.youtube.com/v/vFagaB9M6nQ?fs=1&hl=en_GB" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="155" height="131"> </embed></object> Hi all, I have a script which I coded not long ago which works fine but there is one error which says: Notice: Trying to get property of non-object in /home/www/***-*****.com/hts.php on line 374 I carnt see why its showing the error. $fetch2=mysql_query("SELECT crew FROM users WHERE username='$username'") or die (mysql_error()); $fetch1 = mysql_fetch_object($fetch2); $crewrep1=mysql_query("SELECT * FROM crews WHERE name='$fetch1->crew'") or die (mysql_error()); $crewrep = mysql_fetch_object($crewrep1); $result = $rep + $reps; $result55 = $crewrep->rep + $reps; // Line 374 Can anyone else see why its showing the error? Thanks for your help. Hi all, have constructed a blog through some tutorials which will add and delete messages. I wish to add some form of confirmation box with a yes/no button before deleting but am not sure where to begin. Thanks for any help <?php // Command_BlogDelete.php //############################################################################ // SearchVenueCommand class //############################################################################ class Command_BlogDelete extends Command { //############################################################################ // doExecute //############################################################################ function doExecute(Request $request) { // Get data from request $id = $request->getProperty('id'); // Create manager object $manager = new ManagerMessage(); // Add to database $manager->deleteMessage($id); // Redirect to index header("location:index.php"); } } ?> Hello. I have an object like this: object->object_id object->object_name object->object_number I have an array with many instances of the object, with different values. I want to sort that array to put first the object that the value of object->object_number is higher, and then descending. Please let me know if its not clear! thank you! Hi, I have decided to try and write some OO php. I have a simple class with one function. I am trying to instantiate an object of that class using the new operator but get an error. Parse error: syntax error, unexpected T_OBJECT_OPERATOR in C:\wamp\www\School\addcourse.php on line 38 Code: [Select] <?php $CDBController = new CMasterDataController; //THIS IS LINE 38 CMasterDataController->PerformQuery("SOME SQL HERE"); ?> I am including the file that contains this class (CMasterDataController) in this file (addcourse.php). The version of PHP i am using is 5.3.8. Does anybody know what I am missing? Thanks, Joe I'm curious if anyone has information on how much overhead there is with creating an object in PHP. I've tried finding some benchmarks but haven't really been able to find anything solid to use for reference. Also, when dealing with objects what optimizations can be done to improve performance. I ask because my project I've been working on is entirely OO. Everything, including views, are objects (though their state and behaviour is really just the model they're representing and a show() function that has the HTML used to display the model). This makes development very easy and clean but I'm trying to figure out how much of a difference I can expect in production and in what ways I can limit any negative side effects. What things could be cached, and what things can't? For example, is it possible to cache the class definition without caching instances of that definition (since they'd be different from page view to pageview)? Would that be helpful. Any pointers would be great. I haven't had a lot of time with performance tweaking so I'm not sure of any known pitfalls. I know objects and function calls use a bit more overhead but I've never found out how much more. Thanks in advance. I've been getting this error message: Trying to get property of non-object in /application/controllers/index.php on line 37 Here is line 37 $this->view->title = $pageInfo[0]->title; any help would be much appreciated. I have this SimpleXMLElement Object and I can't echo out any attribute. In this example I am only showing you one SimpleXMLElement Object of the entire result set just for brevity. Here is the code that loops through the results: foreach($oXML->links->link as $o){ echo "<pre>";print_r($o);echo "</pre>"; } SimpleXMLElement Object ( [advertiser-id] => 2860239 [advertiser-name] => Amber Alert GPS [category] => Array ( [0] => children [1] => children ) [click-commission] => Array ( [0] => 0.0 [1] => 0.0 ) [creative-height] => Array ( [0] => 0 [1] => 0 ) [creative-width] => Array ( [0] => 0 [1] => 0 ) [language] => en [lead-commission] => SimpleXMLElement Object ( ) [link-code-html] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [link-code-javascript] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [description] => 20% discount of Amber Alert GPS Child Locator Device when using "Amber2" Promo Code. [destination] => http://www.amberalertgps.com [link-id] => 10745524 [link-name] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [link-type] => Text Link [performance-incentive] => false [promotion-end-date] => SimpleXMLElement Object ( ) [promotion-start-date] => SimpleXMLElement Object ( ) [promotion-type] => coupon [relationship-status] => joined [sale-commission] => 30.00% [seven-day-epc] => N/A [three-month-epc] => 2.66 ) I try to do this but it doesn't work: foreach($oXML->links->link as $o){ echo $o['advertiser-id']; } # I also tried this: foreach($oXML->links->link as $o){ echo $o->advertiser-id; } How do you echo the values? Let assume: Code: [Select] class b { public $varb; function __construct() { $varb = 'something'; } } class a { public $vara; function __construct() { $vara = new b(); } } $obj = new a(); echo($a->$vara->$varb); // Fatal error: cannot access empty property Obviously, the lifetime of object $vara of class b ends at the end of constructor of a. I can understand why, but coming from a cpp background I find this inconvenient. Do I miss something? Is there some operator instead of new, that determines the lifetime? What object oriented alternative approach would you recommend. Thanks for the help. Regards Hello. I am now dumbfounded (once again). I am using $this inside a class. I honestly have no idea what is going on. If anyone could give me a pointer that would be brilliant. Code: [Select] /* * List of functions in this class in order (construct and destruct are the only functions not in alphabetical order) * Construct * BooleanValue * BuildColumns * Connect * Clean * Delete * Disconnect * EndTransaction * Error * Insert * IsConnected * Kill * LastInsertID * Log * Query * RollbackTransaction * RowCount * Select * StartTransaction * Update * Where * Destruct */ class MySQL extends MySQLi { private $host = HOST; private $user = USER; private $pass = PASS; private $data = DATA; private $port = PORT; private $charset = CHARSET; const quote = "'"; // what quote to use /* Internal vars */ private $lastID = ""; private $lastResult = ""; private $queries = ""; private $link = 0; private $timeStart = 0; private $timeEnd = 0; private $timeTotal = 0; private $errorString = ""; private $errorNo = 0; private $in_transaction = false; private $queryQueue = ""; /* * Construct * Starts the connection unless autoconnect = false */ public function __construct($autoconnect = true) { $autoconnect === true ? $this->Connect() : false; } /* * End construct ***************************************************************************************************/ /* * BooleanValue * Determins whether the input is a boolean value, or can be converted into a boolean value */ static function BooleanValue($value) { $value = self::Clean($value); if(gettype($value) == "boolean") { if($value == true) { return true; } else { return false; } } elseif(is_numeric($value)) { if($value > 0) { return true; } else { return false; } } else { $str = strtoupper(mysqli_real_escape_string($this->link, trim($value))); if($str == "ON" || $str == "SELECTED" || $str == "CHECKED" || $str == "YES" || $str == "Y" || $str == "TRUE" || $str == "T") { return true; } else { return false; } } } /* * End BooleanValue ***************************************************************************************************/ /* * BuildColumns * Builds columns for use with SQL statements */ static function BuildColumns($columns, $addQuotes = true, $showAlias = true) { if($addQuotes) { $quote = self::quote; } else { $quote = ""; } switch(gettype($columns)) { case "array": $sql = ""; $i = 0; foreach($columns as $key => $value) { $key = self::Clean($key); $value = self::Clean($value); if($i == 0) { $sql = $quote.$value.$quote; $i = 1; } else { $sql .= ", ".$quote.$value.$quote; } if($showAlias && is_string($key) && (!empty($key))) { $sql .= " AS ".$quote.$key.$quote."'"; } } break; case "string": $columns = self::Clean($columns); return $quote.$columns.$string; break; default; return false; break; } return $sql; } /* * End BuildColumns ***************************************************************************************************/ /* * Connect * Connects to the database */ public function Connect() { $this->link = @mysqli_connect($this->host, $this->user, $this->pass, $this->data, $this->port); $this->IsConnected(); } /* * End Connect ***************************************************************************************************/ /* * Clean * Cleans input */ static function Clean($value) { $this->IsConnected(); $value = ltrim($value); $value = rtrim($value); $value = mysqli_real_escape_string($this->link, $value); return $value; } /* * End Clean ***************************************************************************************************/ /* * Delete * Deletes a record from the database */ public function Delete($table, $whereArray) { $sql = "DELETE FROM ".$table; $sql .= self::Where($whereArray); } /* * End Delete ***************************************************************************************************/ /* * Disconnect * Disconnects from the database */ public function Disconnect() { if($this->IsConnected()) { mysqli_close($this->link); } } /* * End disconnect ***************************************************************************************************/ /* * EndTransaction * Ends the transaction, saving all data to the database */ public function EndTransaction() { $this->IsConnected(); if($this->in_transaction) { if(!mysqli_query($this->link, "COMMIT")) { $this->RollbackTransaction(); } else { $this->in_transaction = false; return true; } } else { $this->Error("Not in a transaction", -1); return false; } } /* * End EndTransaction ***************************************************************************************************/ /* * Error * Handles Errors */ public function Error($errstr = "", $errno = 0) { try { if(strlen($errstr) > 0) { $this->errorString = $errstr; } else { $this->errorString = @mysqli_error($this->link); if(!strlen($this->errorString) > 0) { $this->errorString = "Unknown error"; } } if($errno <> 0) { $this->errorNo = $errno; } else { $this->errorNo = @mysqli_errno($this->link); } } catch(Exception $e) { $this->errorString = $e->getMessage(); $this->errorNo = -999; } $this->Kill(); } /* * End Error ***************************************************************************************************/ /* * Insert * Inserts a record into the database */ public function Insert($table, $valuesArray) { $columns = self::BuildColumns(array_keys($valuesArray), false); $values = self::BuildColumns($valuesArray, true, false); $sql = "INSERT INTO ".$table." (".$columns.") VALUES (".$values.")"; $this->queryQueue .= $sql; } /* * End Insert ***************************************************************************************************/ /* * IsConnected * Checks if there is a connection */ public function IsConnected() { if(@mysqli_ping($this->link)) { return true; } else { $this->Error(); return false; $this->RollbackTransaction(); $this->Kill("No connection present"); } } /* * End IsConnected ***************************************************************************************************/ /* * Kill * Rollsback anychanges and kills the script */ public function Kill() { $this->RollbackTransaction(); if(!$this->errorString) { $this->errorString = "Unknown"; } if(!$this->errorNo) { $this->errorNo = -999; } die("<br /><br /><strong>An error has occured.<br />".$this->errorString."<br />".$this->errorNo); } /* * End Kill ***************************************************************************************************/ /* * LastInsertID * Returns the last inserted ID */ public function LastInsertID() { return $this->lastID; } /* * End LastInsertID ***************************************************************************************************/ /* * Log * Logs all MySQL queries */ static function Log($page, $utime, $wtime, $mysql_time, $sphinx_time, $mysql_count_queries, $mysql_queries) { /*$table = "mysql-".date("Ymd"); $sql = "INSERT DELAYED INTO ".$table." (ip, page, utime, wtime, mysql_time, sphinx_time, mysql_count_queries, mysql_queries, user_agent) VALUES ("self::quote.$_SERVER['REMOTE_ADDR'].self::quote.", ".self::quote.$page.self::quote.", */ } /* * End Log ***************************************************************************************************/ /* * Query * Exectues all queries */ public function Query($sql) { $this->IsConnected(); $this->timeStart = microtime(true); $this->queries = $sql; $this->StartTransaction(); $this->lastResult = @mysqli_query($this->link, $sql); if(!$this->lastResult) { $this->RollbackTransaction(); $this->Error(); } $this->EndTransaction(); if(strpos(strtolower($sql), "insert") === 0) { $this->lastID = mysqli_insert_id($this->link); if($this->lastID === false) { $this->Error(); } else { return $this->lastResult; //$this->queryQueue = ""; } } elseif(strpos(strtolower($sql), "select") === 0) { $this->LastID = 0; } $this->timeEnd = microtime(true); $this->timeTotal = ($this->timeEnd - $this->timeStart); $removeE = explode('E', $this->timeTotal); $this->timeTotal = $removeE[0]; echo $this->queryQueue; } /* * End Query ***************************************************************************************************/ /* * RollbackTransaction * Un-does the changes made */ private function RollbackTransaction() { $this->IsConnected(); if(!mysqli_query($this->link, "ROLLBACK")) { $this->Error("Rollback failed. Manual cleanup required"); return false; } else { $this->in_transaction = false; return true; } } /* * End RollbackTransaction ***************************************************************************************************/ /* * RowCount * Returns the amount of rows effected from the last query */ public function RowCount() { return mysqli_num_rows($this->lastResult); } /* * End RowCount ***************************************************************************************************/ /* * Select * Selects rows * USAGE: * $result = $sql->Select("users", array("username" => "james")); * while($row = mysqli_fetch_array($result)) { * echo $row['password']; * } */ public function Select($table, $whereArray = null, $columns = null, $sortColumns = null, $sortAscending = true, $limit = null) { if(!is_null($columns)) { $sql = self::BuildColumns($columns); } else { $sql = "*"; } $sql = "SELECT ".$sql." FROM ".$table; if(is_array($whereArray)) { $sql .= self::Where($whereArray); } if(!is_null($sortColumns)) { $sql .= " ORDER BY ".self::BuildColumns($sortColumns, true, false). " ".($sortAscending ? "ASC" : "DESC"); } if(!is_null($limit)) { $sql .= " LIMIT ".$limit; } self::Query($sql); $return = ""; return $this->lastResult; } /* * End Select ***************************************************************************************************/ /* * StartTransaction * Starts the transaction */ private function StartTransaction() { if(!$this->IsConnected()) { die(); } if(!$this->in_transaction) { if(!mysqli_query($this->link, "START TRANSACTION")) { $this->Error(); return false; } else { $this->in_transaction = true; return true; } } else { $this->Error("Already in a transaction"); } } /* * End StartTransaction ***************************************************************************************************/ /* * Update * Updates the rows */ public function Update($table, $valuesArray, $whereArray = null) { $sql = ""; $i = 0; foreach($valuesArray as $key => $value) { $key = self::Clean($key); $value = self::Clean($value); if($i == 0) { $sql = $key." = ".self::quote.$value.self::quote; $i = 1; } else { $sql .= ", ".$key." = ".self::quote.$value.self::quote; } } $sql = "UPDATE ".$table." SET ".$sql; if(is_array($whereArray)) { $sql .= self::Where($whereArray); } self::Query($sql); return $this->lastResult; } /* * End Update ***************************************************************************************************/ /* * Where * Select rows where X */ public function Where($whereArray) { $where = ""; foreach($whereArray as $key => $value) { $key = self::Clean($key); $value = self::Clean($value); if(strlen($where == 0)) { if(is_string($key)) { $where = " WHERE ".$key." = ".self::quote.$value.self::quote; } else { $where = " WHERE ".self::quote.$value.self::quote; } } else { if(is_string($key)) { $where .= " AND ".$key." = ".self::quote.$value.self::quote; } else { $where .= " AND ".self::quote.$value.self::quote; } } } return $where; } /* * End where ***************************************************************************************************/ /* * Destruct * Closes the connection and cleans up */ public function __destruct() { if($this->queryQueue) { $this->Query($this->queryQueue); } $this->Disconnect(); } /* * End destruct ***************************************************************************************************/ } The code I am using to get the error is this: Code: [Select] $sql = new Mysql; $sql->Insert("users", array("username" => "James")); $sql->Insert("users", array("username" => "fds")); $sql->Insert("users", array("username" => "le")); Thanks. EDIT: Added code to call the error. New to classes, basic understanding of procedural. I am trying to echo rows from the data base using PDO. Here is the code: Code: [Select] <div id="admin"> <form method="POST" action="categoryAdmin.php"> <table> <tr><th bgcolor="#EEEEEE">Cat Id</th> <th bgcolor="#EEEEEE">Title</th> <th bgcolor="#EEEEEE">Description</th> </tr> <?php global $dbh; $sql = "SELECT * FROM categories"; $sth = $dbh->prepare($sql); $sth-> execute(); print_r($sth); $result = $sth->fetchAll(PDO::FETCH_ASSOC); print_r($result); while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {echo "<tr><td>$row[0]<td><td>$row[1]<td><td>$row[2]<td><tr>\n";} ?> <tr><td><input type="text" name="CatId" size="15" maxlength="10"></td> <td><input type="text" name="CatTitle" size="40" maxlength="130"></td> <td><input type="text" name="CatDesc" size="45" maxlength="200"></td> </tr> </table> <input type="hidden" name="addRecord" value="1"> <input type="submit" name="submit" value="Add Category"> </div> print_r($sth); shows: PDOStatement Object ( [queryString] => SELECT * FROM categories ) print_r($result); shows: Array ( => Array ( [categoryId] => Fitness [title] => Sholder Guy [description] => Fix that sholder and more ) ) fatal error: Call to a member function fetchAll() on a non-object in /home/... the line in question is the while loop. I am not sure what to pass it with reguards to PDO. Thanks - AL Hi everyone, It was recommended that I should make the switch from using procedural code to object oriented code with pdo for queries and such. So, I have been doing some reading on both topics, but am finding it rather hard to wrap my head around. I managed to get a PDO query to work with the help of a tutorial that I found online. My next step is to create an object oriented member registration class. I was wondering if anyone on here could provide any advice as far as the setup goes. I will want my member class to be able to: 1) connect to db 2) gather, validate, and send user data to payment processor 3) receive postback data, insert into database, and notify new member. I have already created these functionalities for other websites using procedural coding so once I get pushed in the right direction I should be find to add the other functionalities, which will include 4) Logging a member in 5) Logging a member out 6) Update member information 7) Change password Forgot password 9) Cancel membership Below is my snippet of PDO code that I wrote. Let me know if you guys would do anything differently. I really appreciate your help in this. Code: [Select] <?php // DECLARE DATABASE CONNECTION VARIABLES // $host = 'localhost'; $database = 'database'; $username = 'user'; $password = 'password'; // CONNECT TO DATABASE // try { $connect = new PDO("mysql:host=$host;dbname=$database", $username, $password); } catch(PDOException $e) { echo $e->getMessage(); } $sql = "SELECT siteInfoPage, siteInfoKeywords, siteInfoDescription FROM siteInfo WHERE siteInfoPage = '$page'"; // FETCH INTO A PDOStatement OBJECT // $query = $connect->query($sql); // ECHO THE NUMBER OF COLUMNS // $data = $query->fetch(PDO::FETCH_OBJ); // ASSIGN TO VARIABLES $page_title = $data->siteInfoPage; $keywords = $data->siteInfoKeywords; $description = $data->siteInfoDescription; // CLOSE THE DATABASE CONNECTION // $connect = null; ?> |