PHP - Php Object Help
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 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! 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'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 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! 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> 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 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. 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 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"); } } ?> 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 Currently, I'm trying to create an OpenGL project which creates a visual for data in a file for an assignment, for example, a pie chart. While I have this pie chart correctly and accurately displaying the data, another part of the assignment is being able to zoom in and move the object, of which I have no idea where to start.
This is the code for the pie chart.
#include "OGLPieChart.h" #include <Windows.h> #include <gl/GL.h> #include <math.h> #include <fstream> #include <sstream> #include <iostream> using namespace std; OGLPieChart::OGLPieChart() { //init the OGLRectangle to a fixed size m_topleft.SetX(-50.0f); m_topleft.SetY(50.0f); m_bottomright.SetX(50.0f); m_bottomright.SetY(-50.0f); } OGLPieChart::~OGLPieChart() { } void OGLPieChart::Render() { float PI = 3.14159; float radius = 200; string DataLine; //Changed from int(s) to float(s) to stop angle equation equalling 0 later on. float NeverMarried = 0; float MarriedCivSpouse = 0; float Widowed = 0; float Divorced = 0; float Seperated = 0; float MarriedSpouseAbsent = 0; //Only reading from file so using ifstream instead of ofstream and fstream ifstream DataFile("..\\.\\adult_test_data.csv"); if (!DataFile.is_open()) { cout << "Unable to open file."; return; } else { string DataLine; while (!DataFile.eof()) { getline(DataFile, DataLine); istringstream StringData(DataLine); while (StringData) { getline(StringData, DataLine, ','); if (DataLine == " Never-married") { NeverMarried += 1; } else if (DataLine == " Married-civ-spouse") { MarriedCivSpouse += 1; } else if (DataLine == " Widowed") { Widowed += 1; } else if (DataLine == " Divorced") { Divorced += 1; } else if (DataLine == " Separated") { Seperated += 1; } else if (DataLine == " Married-spouse-absent") { MarriedSpouseAbsent += 1; } } } } DataFile.close(); int MaritalStatusTotal = (NeverMarried + MarriedCivSpouse + Widowed + Divorced + Seperated + MarriedSpouseAbsent); float NeverMarriedAngle = (NeverMarried / MaritalStatusTotal) * 360; float MarriedCivSpouseAngle = (MarriedCivSpouse / MaritalStatusTotal) * 360; float WidowedAngle = (Widowed / MaritalStatusTotal) * 360; float DivorcedAngle = (Divorced / MaritalStatusTotal) * 360; float SeperatedAngle = (Seperated / MaritalStatusTotal) * 360; float MarriedSpouseAbsentAngle = (MarriedSpouseAbsent / MaritalStatusTotal) * 360; glBegin(GL_TRIANGLE_FAN); glColor3f(0.0f, 1.0f, 1.0f); glVertex2f(0, 0); for (int i = 0; i <= NeverMarriedAngle; i++) { glVertex2f(radius * cos(i * PI / 180), radius * sin(i * PI / 180)); } glEnd(); glBegin(GL_TRIANGLE_FAN); glColor3f(1.0f, 1.0f, 0.0f); glVertex2f(0, 0); for (int j = NeverMarriedAngle; j <= NeverMarriedAngle + MarriedCivSpouseAngle; j++) { glVertex2f(radius * cos(j * PI / 180), radius * sin(j * PI / 180)); } glEnd(); glBegin(GL_TRIANGLE_FAN); glColor3f(0.2, 0.3, 0.8); glVertex2f(0, 0); for (int k = NeverMarriedAngle + MarriedCivSpouseAngle; k <= NeverMarriedAngle + MarriedCivSpouseAngle + WidowedAngle; k++) { glVertex2f(radius * cos(k * PI / 180), radius * sin(k * PI / 180)); } glEnd(); glBegin(GL_TRIANGLE_FAN); glColor3f(0.1, 0.1, 1); glVertex2f(0, 0); for (int a = NeverMarriedAngle + MarriedCivSpouseAngle + WidowedAngle; a <= NeverMarriedAngle + MarriedCivSpouseAngle + WidowedAngle + DivorcedAngle; a++) { glVertex2f(radius * cos(a * PI / 180), radius * sin(a * PI / 180)); } glEnd(); glBegin(GL_TRIANGLE_FAN); glColor3f(0.1, 0.2, 0.4); glVertex2f(0, 0); for (int b = NeverMarriedAngle + MarriedCivSpouseAngle + WidowedAngle + DivorcedAngle; b <= NeverMarriedAngle + MarriedCivSpouseAngle + WidowedAngle + DivorcedAngle + SeperatedAngle; b++) { glVertex2f(radius * cos(b * PI / 180), radius * sin(b * PI / 180)); } glEnd(); glBegin(GL_TRIANGLE_FAN); glColor3f(0.8, 0.3, 0.1); glVertex2f(0, 0); for (int c = NeverMarriedAngle + MarriedCivSpouseAngle + WidowedAngle + DivorcedAngle + SeperatedAngle; c <= NeverMarriedAngle + MarriedCivSpouseAngle + WidowedAngle + DivorcedAngle + SeperatedAngle + MarriedSpouseAbsentAngle; c++) { glVertex2f(radius * cos(c * PI / 180), radius * sin(c * PI / 180)); } glEnd(); } bool OGLPieChart::MouseMove( int x, int y ) { m_topleft.SetX( (float) x ); m_topleft.SetY( (float) y ); m_bottomright.SetX( (float) x + 100.0f ); m_bottomright.SetY( (float) y + 100.0f); return true; } bool OGLPieChart::MouseLBUp( int x, int y ) { return true; } bool OGLPieChart::MouseLBDown( int x, int y ) { return true; }And it produces this result: Unfortunately, a constraint for this assignment is that we cannot use GLUT, it is an optional constraint but it would lose me 8% should I use it. Any help with zooming and panning it would be extremely appreciated. I am passing an array in the following function and want my data to be added in the table .Here is the statement Code: [Select] public function insert_data($user_info) { try{ $dbh = new PDO("mysql:host=localhost;dbname=phpfaqproject",'root',''); //echo "connected"; } catch(PDOException $e){ echo $e-> getMessage(); } $sql ="INSERT INTO account (username, userpassword, email, role, location, interest, homepage) VALUES ('" .$user_info['username']."','".$user_info['password'] ."','".$user_info['email']."', 'user','".$user_info['location']."','".$user_info['interests'] ."','".$user_info['homepage']."')"; echo $query."<br />"; $stmt = $dbh->prepare($query); $stmt->execute(); } I don't know why it is not updating the tble although echo $query gives correct results. My code; $sql = "SELECT SUM(IF(`submitdate` IS NULL , 1 , 0 )) as 'Survey Started But Not Completed' FROM `survey_$surveyid`"; $statement = $dbh->prepare($sql); $statement->execute(); $result = $statement->fetch(PDO::FETCH_OBJ); //pass that data to an objectIs returning; stdClass Object ( [Survey Started But Not Completed] => ) I need to set this to a vaule that I can actually print out on the screen... Like a "0" for example. At the moment it is just a NULL. How do I do this?? These don't work; $result = 0; $result = array(['Survey Started But Not Completed'] => "0"); 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 |