PHP - Object Orientation Question
I have instantiated a object and the constructor has an other object added the issue arises when I extent the first object how do I access the object in the variable. below is a stripped down example. I want accessfoo to access class a method foo that is stored in a var in class b is this possible.
Code: [Select] class a { private function foo(){ return "hello word"; } } $a = new a() class b { private $obj; public function __construct ($obj){ $this->obj= $obj; } } class c extends b{ private function accessfoo(){ $this->obj ????????????? } $c = new class($a) Similar TutorialsSo I'm getting a "Notice: Trying to get property of non-object in" error when I'm trying to pull data from a xml. I have a complete xml that has all of the potential node that it could ever have and it loads up fine -no errors, but when I load a different xml that doesn't have all of the possible nodes it returns this error several times here is a sample of my code: $source = 'TestFile.xml'; $xml = new SimpleXMLElement($source,null,true); $result = mysql_query("SELECT * FROM tblvalues") or die(mysql_error()); //Return the table row by row while($row = mysql_fetch_array($result)) { $curblk = substr($row['fldelement'],0,3); switch ($row['fldelement']){ case "E06_04": case "E06_05": case "E06_07": case "E06_08": $cursub = $curblk."_04_0"; $xmlVal = $xml->Header->Record->$curblk->$cursub->$row['fldelement']; //grab value from xml break; ... ... ... // the cases go on for a while... ... case "E07_05": case "E07_06": case "E07_07": case "E07_08": $cursub = $curblk."_03_0"; $cursub2 = $curblk."_05_0"; $xmlVal = $xml->Header->Record->$curblk->$cursub->$cursub2->$row['fldelement']; //this is the line that the error points to break; ... ... ... And here is the sample of the xml that returns the error: Code: [Select] <E07> <E07_01>-20</E07_01> <E07_02>0</E07_02> <E07_15>-25</E07_15> <E07_16>-25</E07_16> <E07_17>-25</E07_17> <E07_18_0> <E07_18_01> <E07_18>-20</E07_18> <E07_19>-20</E07_19> <E07_20>-20</E07_20> </E07_18_01> .... .... .... The obvious problem (to me) is that my code is trying to return a value from a nonexistent xml node, for example: $xmlVal = $xml->Header->Record->$curblk->$cursub->$cursub2->$row['fldelement']; is looking for: $xmlVal = $xml->Header->Record->E07->E07_03_0->E07_05_0->E07_05 Ok, I get that, so how do I rewrite this so it's not blowing up on something so simple? Quick notes: -This same code works for a more complete xml -Rewriting the xmls is not an option as I have no control over those Edit: Almost forgot, thanks! Hi Guys
I am using media queries to set a different CSS if a mobile device. I am using 100% width on certain containers but the styling is using 100% based on the landscape orientation and not whichever way the device is being displayed.
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
.slicknav_menu{
visibility:visible; Hello,
I have a pretty basic two panel design, no code yet but it is pretty straight forward
What I'm concerned about is how a website can react to an orientation change, not simply be re sizing but by relocating items.
So in portrait mode, I have panel a, the top half say 50%, and panel b, 50% bottom half
I rotate it (the phone) to the left of my perspective (viewer) and the top panel goes to the left, and the bottom panel goes to the right.
In the meantime some scrolling animation is in play and the direction of the scroll changes, from sideways to up and down...
Is that possible without refreshing the page?
Edited by greenace92, 04 December 2014 - 04:53 AM. Hi, I want to create a function that reads the exif orientation data of an image and rotates it as required - needs to run before before the resize function here, I'm using GD library if that is relevant: function resize_gd($sourceFileName, $folder, $destinationFileName, $newWidth, $newHeight, $keepProportion) { $newWidth = (int)$newWidth; $newHeight = (int)$newHeight; if (!$this->gdInfo >= 1 || !$this->checkGdFileType($sourceFileName)) { return false; } $img = &$this->getImg($sourceFileName); if ($this->hasError()) { return false; } $srcWidth = ImageSX($img); $srcHeight = ImageSY($img); if ( $keepProportion && ($newWidth != 0 && $srcWidth<$newWidth) && ($newHeight!=0 && $srcHeight<$newHeight) ) { if ($sourceFileName != $folder . $destinationFileName) { @copy($sourceFileName, $folder . $destinationFileName); } return true; } if ($keepProportion == true) { if ($newWidth != 0 && $newHeight != 0) { $ratioWidth = $srcWidth/$newWidth; $ratioHeight = $srcHeight/$newHeight; if ($ratioWidth < $ratioHeight) { $destWidth = $srcWidth/$ratioHeight; $destHeight = $newHeight; } else { $destWidth = $newWidth; $destHeight = $srcHeight/$ratioWidth; } } else { if ($newWidth != 0) { $ratioWidth = $srcWidth/$newWidth; $destWidth = $newWidth; $destHeight = $srcHeight/$ratioWidth; } else if ($newHeight != 0) { $ratioHeight = $srcHeight/$newHeight; $destHeight = $newHeight; $destWidth = $srcWidth/$ratioHeight; } else { $destWidth = $srcWidth; $destHeight = $srcHeight; } } } else { $destWidth = $newWidth; $destHeight = $newHeight; } $destWidth = round($destWidth); $destHeight = round($destHeight); if ($destWidth < 1) $destWidth = 1; if ($destHeight < 1) $destHeight = 1; $destImage = &$this->getImageCreate($destWidth, $destHeight);Edited June 7, 2019 by mcfc4heatons I can call the following function successfully as a single php program // Acknowledge and clear the orders function ack($client, $merchant, $id) { $docs = array('string' => $id); $params = array('merchant' => $merchant, 'documentIdentifierArray' => $docs); $result = $client->call('postDocumentDownloadAck', $params); return $result; } with $result = ack($t, $merchant,'2779540483'); successful output [documentDownloadAckProcessingStatus] => _SUCCESSFUL_ [documentID] => 2779540483 I'm trying to figure out how to call this function as an object from another program. Trying the following gives error ***Call to a member function call() on a non-object*** function postDocumentDownloadAck($t, $merchant, $id) { $this->error = null; $docs = array('string' => $this->id); $params = array('merchant' => $this->merchant, 'documentIdentifierArray' => $docs); ** I've tried the following which does nothing $result = $this->soap->call('postDocumentDownloadAck', $params); ** I've tried the following - which gives error "Call to a member function call() on a non-object" $result = $this->t->soap->call('postDocumentDownloadAck', $params); if($this->soap->fault) { $this->error = $result; return false; } return $result; } *** calling program snippet for above function $merchant= array( "merchant"=> $merchantid, "merchantName" => $merchantname, "email"=> $login, "password"=> $password); $t = new AmazonMerchantAPI($merchantid, $merchantname, $login, $password); $documentlist= $t->GetAllPendingDocumentInfo('_GET_ORDERS_DATA_'); $docid = $documentlist['MerchantDocumentInfo'][$i]['documentID']; $docs = array('string' => $docid); $ackorders = $t->postDocumentDownloadAck($t, $merchant,$docs); Any ideas of what I'm doing wrong are greatly appreciated. Hey 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! when in a form, I wish to build a conditional that if the response to a radio button is a value of 2 (female), it will display an input requesting for users maiden name. If not 2 goes to the next input statement. Here is code I was experimenting with: <html> <body> <form action="" name="test" method='POST'> <input type="radio" id="sex" value=1 checked><label>Male</label> <input type="radio" id="sex" value=2><label>Femaleale</label> <?php $result = "value"; if ($result == 2) echo "<input type='int' id='gradYear' size='3' required>"; else echo "Not a female!" ?> <input type="submit" value="GO"> </form> </body> </html> The code passes debug, however, Not a Female is displayed. My question is - Can I do this and if so, what value do I test against id='sex' or value. I tried each one but gave the same results. I realize that $_POST[sex] would be used after the submit button is clicked. But this has me stumped. Thanks for the assis in advance. 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> 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 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 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'); } } ?> 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)? 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. 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? Hello, I have some questions here on PHP Object-Oriented. I started learning PHP Procedural since some months, and I am doing quite well. I want to start with PHP Object-Oriented now, but the problems, I have not found a good easy readable tutorial on it. I have watched some videos on YouTube, but the way they explained it made me confused. I want to know something from you, if you are an experienced PHP programmer. I want to work on CMS like Drupal, WordPress, Magento and Prestashop because I have noticed a rise in job availability in these fields in my country. 1/ Is it necessary to know PHP Object-Oriented to work as Drupal, Magento or Prestashop developers? (Note: I have a blog on WordPress, and I have huge experienced on the Dashboard, configurations and so on...) 2/ Can I start learning frameworks like CodeIgniter without learning PHP Object-Oriented? Thank you.. Perhaps the questions may have not sense for you, but I just want to know your opinions. Please, if you are an experienced programmer, you reply me. I am currently trying to implement Ajax into a new chat function, however in the database under messages it keeps showing up as: [object HTMLInputElement] but the date (CURRENT_TIMESTAMP) works fine. Why does it do this? Here is the main code for the page: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript" src="jquery-1.4.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("form#submit").submit(function() { // we want to store the values from the form input box, then send via ajax below var fname = $('#Messages').attr('value'); $.ajax({ type: "POST", url: "ajax2.php", data: "Messages="+ Messages, success: function(){ $('form#submit').hide(function(){$('div.success').fadeIn();}); } }); return false; }); }); </script> </head> <body> <div class="container"> <form id="submit" method="post"> <fieldset> <legend>Enter Information</legend> <label for="Messages">Message:</label> <input id="Messages" class="text" name="Messages" size="20" type="text"> <button class="button positive">Submit comment!</button> </fieldset> </form> <div class="success" style="display:none;">Comment has been added.</div> </div> </body> </html> Ajax2.php file: Code: [Select] <?php $con = mysql_connect("x","x","x"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("x", $con); // CLIENT INFORMATION $Messages = htmlspecialchars(trim($_POST['Messages'])); $addClient = "INSERT INTO Comments (Messages,Date) VALUES ('$Messages', CURRENT_TIMESTAMP)"; mysql_query($addClient) or die(mysql_error()); ?> Any help would be greatly appreciated, Thanks, otester |