PHP - Need Some Help With Php Object Code !!
Hi, everyone. I'm having a problem with getting the result from my php code.
Code: [Select] <?php class Mysql{ private $host; private $user; private $pass; private $db; public function __construct(){ $this->host = "localhost"; $this->user = "root"; $this->pass = "password"; $this->db = "person"; $this->conn(); } private function conn(){ $conn = mysql_connect($this->host, $this->user, $this->pass); if(!$conn){ mysql_error(); }else{ mysql_select_db($this->db, $conn); } } public function query($sql){ $result = mysql_query($sql); return $result; } public function fetch_array($result){ return mysql_fetch_array($result); } public function num_rows($result){ return mysql_num_rows($result); } } $db = new Mysql(); /******************************************************************************************/ class Person{ public $id; public $name; public function show_all(){ return $this->by_sql("SELECT * FROM USERS"); } public function show_by_id($id){ return $this->by_sql("SELECT * FROM USERS WHERE id = {$id} LIMIT 1"); } public function show_by_name($n){ return $this->by_sql("SELECT * FROM USERS WHERE name = {$n}"); } private function by_sql($sql){ global $db; $result = $db->query($sql); $arr = array(); while ($r = $db->fetch_array($result)){ $arr[] = $this->initiate($r); } return $arr; } private function initiate($r){ $obj = new self; foreach ($r as $att=>$val){ $obj->$att = $val; } return $obj; } } ?> Code: [Select] <?php //phpinfo(); require_once("obj.php"); $user = new Person(); echo $user->show_by_id(1); ?> 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)? 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! 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 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 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 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. 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! 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 I thought I was deleting (unset) an object, but when adding a destructor, found it was never being fired. I then used debug_zval_dump() and found that my refcount is 7, and it is my understanding that it must be 3 (more on why I think this later). I searched where I might have left a copy, but couldn't find it. Any recommendations how to do so? I looked for ways to find all references to an object https://www.php.net/manual/en/language.references.spot.php seems to be on topic, but doesn't say much? https://www.php.net/manual/en/features.gc.refcounting-basics.php seems to imply that xdebug_debug_zval() might help, but I haven't installed http://xdebug.org/ and haven't tested yet. https://stackoverflow.com/questions/2893672/is-there-any-way-to-access-all-references-to-given-object doesn't say muchAfter manually searching and not finding exactly what I was looking for, I came across this script. public function addGatewayClient(GatewayClient $client):TimerInterface { return $this->loop->addPeriodicTimer($this->period, function() use($client) { // bla bla bla }); }
<?php ini_set('display_errors', 1); class MyClass { public function __destruct() { echo('__destruct'.PHP_EOL); } } function getZval($v):string { ob_start(); debug_zval_dump($v); $rs = ob_get_clean(); return str_replace(PHP_EOL, '', $rs); } $obj = new MyClass; echo('create object: '.getZval($obj).PHP_EOL); $objC1 = $obj; echo('save first reference: '.getZval($obj).PHP_EOL); $objC2 = $obj; echo('save second reference: '.getZval($obj).PHP_EOL); // This is the line to comment out $func = function() use($obj) {}; echo('set function: '.getZval($obj).PHP_EOL); unset($objC1); echo('delete first reference: '.getZval($obj).PHP_EOL); unset($objC2); echo('delete second reference: '.getZval($obj).PHP_EOL); unset($obj); echo('Done'.PHP_EOL); If I comment out \\$func = function() use($obj) {};, I see the refcount start at 3, go up to 5 and then back down to 3, then __destruct() being called, and then the script completion "Done". But then when I don't comment the closure function, I see it go up to 6, go down to 4, the script completion "Done", and then __destruct() being called. Guess I can just set the object to be deleted to NULL, but I feel there should be a better way. Any recommendations? On a side note, debug_zval_dump() is more difficult in the real world if there is recursion, and my getZval() function results in a fatal error by exhausting too much memory. I also tried just calling debug_zval_dump(), but it definitely wasn't a good call. 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. 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? 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. 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? 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. |