PHP - Graph Generation Script - I Think I've Got My Class Format Wrong!
Hello,
I am using a tutorial script for generating a basic bar graph. I have attempted to convert this script into an object-oriented script. However, upon attempting to define the graph, it is not successfully generated. Here is my code: Code: [Select] <? class Graph { var $values; var $image; var $image_width = 450; var $image_height = 300; var $margin = 20; var $bar_size = 20; var $horizontal_lines = 20; var $bar_colour; var $border_colour; var $background_colour; var $line_colour; function CreateGraph() { $this->image = imagecreate($this->image_width, $this->image_height); } function SetSize($width, $height) { $this->image_width = $width; $this->image_height = $height; } function SetMargin($size) { $this->margin = $size; } function SetBarSize($size) { $this->bar_size = $size; } function SetHorLines($size) { $this->horizontal_lines = $size; } function HexConvert($rgb) { return array( base_convert(substr($rgb, 0, 2), 16, 10), base_convert(substr($rgb, 2, 2), 16, 10), base_convert(substr($rgb, 4, 2), 16, 10), ); } function SetColours($bars, $background, $border, $line) { // This is hex based, similar to CSS, it is converted by HexConvert $bars = $this->HexConvert($bars); $background= $this->HexConvert($background); $border= $this->HexConvert($border); $line = $this->HexConvert($line); $this->bar_colour = imagecolorallocate($this->image, $bars[0], $bars[1], $bars[2]); $this->background_colour = imagecolorallocate($this->image, $background[0], $background[1], $background[2]); $this->border_colour = imagecolorallocate($this->image, $border[0], $border[1], $border[2]); $this->line_colour =imagecolorallocate($this->image, $line [0], $line [1], $line [2]); } function DrawBorders() { imagefilledrectangle($this->image,1,1,$this->image_width-2,$this->image_height-2,$this->border_colour); imagefilledrectangle($this->image,$this->margin,$this->margin,$this->image_width-1-$this->margin,$this->image_height-1-$this->margin,$this->background_colour); } function DrawHorLines($horizontal_gap, $ratio) { for($i=1;$i<=$this->horizontal_lines;$i++) { $y = $this->image_height - $this->margin - $horizontal_gap * $i ; imageline($this->image, $this->margin, $y, $this->image_width - $this->margin, $y, $this->line_colour); $v = intval($horizontal_gap * $i / $ratio); imagestring($this->image, 0, 5, $y-5, $v, $this->bar_colour); } } function DrawBars($graph_height, $gap, $ratio) { for($i=0;$i< $total_bars; $i++) { list($key,$value)=each($this->values); $x1= $this->margin + $gap + $i * ($gap+$this->bar_size) ; $x2= $x1 + $this->bar_size; $y1 = $this->margin +$graph_height- intval($value * $ratio) ; $y2 = $this->image_height-$this->margin; imagestring($this->image,0,$x1+3,$y1-10,$value,$this->bar_colour); imagestring($this->image,0,$x1+3,$this->image_height-15,$key,$this->bar_colour); imagefilledrectangle($this->image,$x1,$y1,$x2,$y2,$this->bar_colour); } } function DrawGraph() { $graph_width=$this->image_width - $this->margin * 2; $graph_height=$this->image_height - $this->margin * 2; $total_bars = count($values); $gap = ($graph_width- $total_bars * $this->bar_width ) / ($total_bars +1); $this->DrawBorders(); $max_value=max($values); $ratio = $graph_height / $max_value; $horizontal_gap = $graph_height / $horizontal_lines; $this->DrawHorLines($horizontal_gap, $ratio); $this->DrawBars($graph_height, $gap, $ratio); } function OutputGraph() { header("Content-type:image/png"); imagepng($this->image); } } ?> I expect this to be my misunderstanding of how object orientated codes work. I'm also open to any suggestions for improvement. Edit: Here is the script where I use the class. Code: [Select] <? include "bargraph.class.php"; $graph = new Graph; $graph->SetSize(450, 300); $graph->CreateGraph(); $graph->SetMargin(20); $graph->SetBarSize(20); $graph->SetHorLines(20); $graph->SetColours("FFFFFF", "C0C0C0", "000000", "000000"); $graph->DrawGraph(); $graph->OutputGraph(); ?> Similar Tutorialshi, I hope some one can be of help? I want to make a graph using php and GD with data from MySQL, so far success. Now I want to ammend the script (see end of message) to display text on each bar, e.g red, green, blue. Also currently I loop through when setting the bar colours, in this case grey, how can I get it so there are 3 different colours? There will only ever be 3 bars. Thank you for any help Gary Code: [Select] <?php $dbhost = 'host'; $dbuser = 'user'; $dbpass = 'password'; $dbname = 'db'; $tblname = 'tbl'; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); mysql_select_db($dbname); // Make a MySQL Connection $query = sql goes here! $result = mysql_query($query) or die(mysql_error()); $values = array(); // Print out result while($row = mysql_fetch_array($result)){ array_push($values,$row['COUNT(Answer)']);} // This array of values is just here for the example. //$values = array("5","6","7"); // Get the total number of columns we are going to plot $columns = count($values); // Get the height and width of the final image $width = 150; $height = 200; // Set the amount of space between each column $padding = 15; // Get the width of 1 column $column_width = $width / $columns ; // Generate the image variables $im = imagecreate($width,$height); $gray = imagecolorallocate ($im,0xcc,0xcc,0xcc); $gray_lite = imagecolorallocate ($im,0xee,0xee,0xee); $gray_dark = imagecolorallocate ($im,0x7f,0x7f,0x7f); $white = imagecolorallocate ($im,0xff,0xff,0xff); // Fill in the background of the image imagefilledrectangle($im,0,0,$width,$height,$white); $maxv = 0; // Calculate the maximum value we are going to plot for($i=0;$i<$columns;$i++)$maxv = max($values[$i],$maxv); // Now plot each column for($i=0;$i<$columns;$i++) { $column_height = ($height / 100) * (( $values[$i] / $maxv) *100); $x1 = $i*$column_width; $y1 = $height-$column_height; $x2 = (($i+1)*$column_width)-$padding; $y2 = $height; imagefilledrectangle($im,$x1,$y1,$x2,$y2,$gray); // imagefilledrectangle($im,$x1,$y1,$x2,$y2,$colour[$i]); // This part is just for 3D effect imageline($im,$x1,$y1,$x1,$y2,$gray_lite); imageline($im,$x1,$y2,$x2,$y2,$gray_lite); imageline($im,$x2,$y1,$x2,$y2,$gray_dark); } // Send the PNG header information. Replace for JPEG or GIF or whatever header ("Content-type: image/png"); imagepng($im); ?> I wrote this basic script yesterday to process and generate a Google Site Map. And it works! BUT I want to advance this script to accommodate for something else and I don't know the correct path to take from here, but I will tell you what I've found out so far.. Current Situation: 1 - Currently my below script generates urls in the site map like: http://abcdefg.com/index.php?dispatch=products.view&product_id=29826 2 - I have .htaccess configured to rewrite the urls to the products name data like: http://abcdefg.com/pennies/wheat-pennies/lincoln-wheat-penny-cent.html (just an example) and these urls are ONLY active if clicking on the site links themselves - meaning if I enter: http://abcdefg.com/index.php?dispatch=products.view&product_id=29826 directly into the url, the url does not resolve to this natural friendly url name. What Id like to achieve (which I don't know what direction I should be looking!): - I'd like my xml output urls (as current) to be written in the natural format (as in #2 above). FYI here is a current example output item in my sitemap: Code: [Select] <url> <loc>http://abcdefg.com/index.php?dispatch=products.view&product_id=29803</loc> <changefreq>weekly</changefreq> <lastmod>2010-09-24T08:00:00+04:00</lastmod> </url> Can anyone give me some guidance on what method might work for this? Do you think it's more a mod_rewrite issue? Or can this be handled easier with straight up modifications to my below? I'm just a bit confused on what direction I should be looking.. Thanks for any input. <?php header("Content-Type: text/xml;charset=iso-8859-1"); echo '<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'; //include('config.local.php'); $cxn = mysqli_connect($config['db_host'], $config['db_user'], $config['db_password'], $config['db_name']); $query = "SELECT cscart_product_descriptions.product_id, cscart_products.product_id, cscart_products.timestamp FROM cscart_product_descriptions JOIN cscart_products ON cscart_product_descriptions.product_id = cscart_products.product_id WHERE cscart_products.status='A' LIMIT 10000"; $result = mysqli_query($cxn, $query); $row = mysqli_fetch_array($result); while ($row = mysqli_fetch_array($result)) { $formatedTime = $row['timestamp']; echo '<url> <loc>http://abcdefg.com/index.php?dispatch=products.view&product_id=' . $row['product_id'] . '</loc> <changefreq>weekly</changefreq> <lastmod>'. date('c',$formatedTime) .'</lastmod> </url>'; } //while ($row = mysqli_fetch_array($result)) echo '</urlset>'; ?> What are some common standards to writing a php class? One thing I think is a standard is using "Camel Case" (example): public function myFunctionName instead of using: public function my_function_name Is that true, and are there any others that you know about? I would like to hear what they are! Thanks! OK, Here is the code $sql = "SELECT TrialListing.listingID AS Trial, TrialClass.classID AS Class, place.place_name AS Place, CONCAT_WS( ' ', pedigree.pretitle, pedigree.`Name`) AS Hound, CONCAT_WS( ' ', ped2.pretitle, ped2. NAME )AS Sire, CONCAT_WS( ' ', ped3.pretitle, ped3. NAME )AS Dam, pedigree.Breeder, pedigree.`Owner`, CASE WHEN placement.place_id < 5 THEN TRUNCATE(TrialClass.number_of_entrants / placement.place_id,2) WHEN placement.place_id = 5 THEN '' ELSE 0 END AS Score FROM TrialListing Left Join TrialClass ON TrialListing.listingID = TrialClass.listingID JOIN placement ON placement.event_id = TrialClass.trialClassID JOIN pedigree ON pedigree.PedigreeId = placement.hound_id LEFT OUTER JOIN pedigree AS ped2 ON pedigree.SireId = ped2.PedigreeId LEFT OUTER JOIN pedigree AS ped3 ON pedigree.DamId = ped3.PedigreeId LEFT JOIN place ON place.place_id = placement.place_id WHERE TrialListing.listingID = 11 ORDER BY Class, FIELD(place.place_id, '1', '2', '3', '4', '0') "; // Database Query $result = mysql_query("$sql"); // Database Query result $num_rows = mysql_num_rows($result); // Starts the table echo "<table class=\"clubList\">\n <tr> <th>trialID</th> <th>ClassID</th> <th>Place</th> <th>Hound</th> <th>Sire</th> <th>Dam</th> <th>Score</th> </tr>"; // Create the contents of the table. for( $i = 0; $i < $row = mysql_fetch_array($result); $i++){ echo "<tr>\n" ."<td>".$row["Trial"]."</td>\n" ."<td>".$row["Class"]."</td>\n" ."<td>".$row["Place"]."</td>\n" ."<td>".$row["Hound"]."</td>\n" ."<td>".$row["Sire"]."</td>\n" ."<td>".$row["Dam"]."</td>\n" ."<td>".$row["Score"]."</td>\n" ."</tr>";} echo "</TABLE>"; Here is the output, I added the TrialID & ClassID for informational purposes, they do not need to be displayed in the live table. trialID ClassID Place Hound Sire Dam Score 11 1 1st Eaton Brook Tug Hill Tatonka Eaton Brook Hickety Hawk Eaton Brook Gunner's Beulah 43.00 11 1 2nd FC North Bend Igloo FC DFJ Murphy White IFC Brad-Ju's Bella Donna 21.50 11 1 3rd FC North Bend Igloo FC DFJ Murphy White IFC Brad-Ju's Bella Donna 14.33 11 1 4th Rail Road Spike VI Elwell's Mike Elwell's Hannah 10.75 11 1 NBQ FC Fish Creek Spike Fish Creek Bull II Fish Creek Susie [H849395] 11 2 1st Enman Hill Sweet Poppy FTCH Straight Arrow Lucky of Coos 32.00 11 2 2nd Fishflakes Penny At Harehaven FTCH Jill's Fair-Isle Spud FTCH Millbridge Brownie 16.00 11 2 3rd Line Elm Flakers IFC Flakers Rex IFC Line Elm Ginger 10.66 11 2 4th FTCH Fareast Mookie FTCH Mellowrun Sly FTCH Cape Breton Maude 8.00 11 2 NBQ FTCH Mellowrun Sly Mellowrun Skylighter FTCH Mellowrun Becka 11 3 1st Bojangle V Lee Otworth Half Acre's Cocoa Candy 23.00 11 3 2nd Gay Doll Gay Roll II Gay Idol 11.50 11 3 3rd Bruce's Blue Lady FC Kilsock's Blue Creek Bart Bishopville's Zippy 7.66 11 3 4th FC Pearson Creek Barbin FC Pearson Creek Barbarian FC B-Line Stubby 5.75 11 3 NBQ Sims Creek Cricket Ronnie Joe Sims Creek Tiny 11 4 1st FTCH Fareast Mookie FTCH Mellowrun Sly FTCH Cape Breton Maude 26.00 11 4 2nd FTCH Mellowrun Sly Mellowrun Skylighter FTCH Mellowrun Becka 13.00 11 4 3rd Fishflakes Penny At Harehaven FTCH Jill's Fair-Isle Spud FTCH Millbridge Brownie 8.66 11 4 4th Enman Hill Sweet Poppy FTCH Straight Arrow Lucky of Coos 6.50 11 4 NBQ Line Elm Flakers IFC Flakers Rex IFC Line Elm Ginger Below is what I would like to generate. How do I word or nest the proper PHP code/loops to accomplish this? ClassID Place Hound Sire Dam Score 1st Eaton Brook Tug Hill Tatonka Eaton Brook Hickety Hawk Eaton Brook Gunner's Beulah 43.00 2nd FC North Bend Igloo FC DFJ Murphy White IFC Brad-Ju's Bella Donna 21.50 3rd FC North Bend Igloo FC DFJ Murphy White IFC Brad-Ju's Bella Donna 14.33 4th Rail Road Spike VI Elwell's Mike Elwell's Hannah 10.75 NBQ FC Fish Creek Spike Fish Creek Bull II Fish Creek Susie [H849395] ClassID Place Hound Sire Dam Score 1st Enman Hill Sweet Poppy FTCH Straight Arrow Lucky of Coos 32.00 2nd Fishflakes Penny At Harehaven FTCH Jill's Fair-Isle Spud FTCH Millbridge Brownie 16.00 3rd Line Elm Flakers IFC Flakers Rex IFC Line Elm Ginger 10.66 4th FTCH Fareast Mookie FTCH Mellowrun Sly FTCH Cape Breton Maude 8.00 NBQ FTCH Mellowrun Sly Mellowrun Skylighter FTCH Mellowrun Becka ClassID Place Hound Sire Dam Score 1st Bojangle V Lee Otworth Half Acre's Cocoa Candy 23.00 2nd Gay Doll Gay Roll II Gay Idol 11.50 3rd Bruce's Blue Lady FC Kilsock's Blue Creek Bart Bishopville's Zippy 7.66 4th FC Pearson Creek Barbin FC Pearson Creek Barbarian FC B-Line Stubby 5.75 NBQ Sims Creek Cricket Ronnie Joe Sims Creek Tiny ClassID Place Hound Sire Dam Score 1st FTCH Fareast Mookie FTCH Mellowrun Sly FTCH Cape Breton Maude 26.00 2nd FTCH Mellowrun Sly Mellowrun Skylighter FTCH Mellowrun Becka 13.00 3rd Fishflakes Penny At Harehaven FTCH Jill's Fair-Isle Spud FTCH Millbridge Brownie 8.66 4th Enman Hill Sweet Poppy FTCH Straight Arrow Lucky of Coos 6.50 NBQ Line Elm Flakers IFC Flakers Rex IFC Line Elm Ginger its been over 3 years since i last modded this script.... well its been 3 years since i have done any scripting! and even back then i was very amateurish!! i tried to run the install file and its telling me theres a fault in "line 3" of this script. <?php include("config.php"); session_start(); if (session_is_registered("user") || session_is_registered("pass")) { // <----LINE 3 include("config.php"); ?> <html> <head> <title><?php print "$title - $site_com"; ?></title> <link rel=stylesheet href=style.css> </head> <body leftmargin=0 rightmargin=0 onload="window.status='<?php print "$site_com"; ?>'"> <?php print "<br><center><a href=news.php>Click Here To Log back in</a><br><br><a href=logout.php>Log Out</a></center>"; exit; } ?> <html> <head> <title><-UNDERGROUND-> [BETA]</title> <link rel=stylesheet href=style.css> </head> <body> <center> <table class=td cellpadding=0 cellspacing=0 width=700><tr><td style="border-bottom: solid black 1px;" bgcolor=eeeeee align=right><b>Gamers-Fusion Version 2.5</td></tr><tr><td align=center> It says error unexpecting T_ELSE on line 50...Any help is appreciated <?php if (is_uploaded_file($file_tmp)){ ///SUPPORTED IMAGE TYPES $tgif = "IMAGETYPE_GIF"; $tjpeg = "IMAGETYPE_JPEG"; $tpng = "IMAGETYPE_PNG"; $twsf = "IMAGETYPE_SWF"; $tbmp = "IMAGETYPE_BMP"; $file_size = $_FILES["file"]["size"]; $file_tmp = $_FILES['file']['tmp_name']; $file_name = $_FILES["file"]["name"] ; $file_type = $_FILES["file"]["type"]; $file = $file_name . $file_type; $path = "images/" . $title_id . "/"; $path - $path . basename($file_name); if (exif_imagetype('$file') != $tgif || $tjpeg || $tjpng || $twsf || $tbmp){ if ($file_size < 20000000){ /////20mb///// if (file_exists($path . $file_name)){ if (move_uploaded_file($file_tmp,$path)){ $msg = "File upload successful"; } else{ $msg = "There was an error"; } }else{ $msg = "This file already exists on the server"; { }else{ $msg = "File size is too large"; } }else{ $msg = "File type not supported"; } }else{ $file = ""; } ?> im getting a warning saying 'Warning: mkdir() [function.mkdir]: File exists in /home/multisea/public_html/BSGN/secure_upload.php on line 5' if i execute the script below Code: [Select] <?php $secure_folder = "upimg/$rand/$time"; $rand=rand(0000000000,9999999999); $time=time(); mkdir("$secure_folder", 0777); echo "secure folder made successfully... not done yet so dont close this window..."; $target = "$secure_folder"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; if ($uploaded_size > 1500000) { echo "Your file is too large.<br>"; $ok=0; } if ($ok==0) { echo "sorry your file was not uploaded..."; } else {if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) {echo "the file ". basename( $_FILES['uploadedfile']['name']). "hasbeen uploaded the link to your file is http://multi-search.org/BSGN/$secure_folder/". basename( $_FILES['uploaded']['name'])."<br />"; } else {echo "sorry, there was a problem uploading your file."; } } ?> hi guys i have been building a website and have added a contact form and PHP script to send me a email server side the script works as it it will refresh the pages and display my thank you message but no email ever turns up my email address is correct so there must be somthing else not working <?php /*Email Varibles*/ $emailSubject = 'media-ondemand-contact.php'; $webMaster = 'alextrashacc@hotmail.com'; /*Data Varibles*/ $email = $_POST['email']; $name = $_POST['name']; $radiobuttons = $_POST['radiobuttons']; $where = $_POST['where']; $comments = $_POST['comments']; $newsletter = $_POST['newsletter']; $body = <<<EOD <br><hr><br> Email: $email <br> Name: $name <br> Suggestions Ect: $radiobuttons <br> Where did you hear about us: $where <br> Comments: $comments <br> News Letter Sign up: $newsletter $headers = "$email\r\n"; $headers .= "Content-type: text/html\r\n"; $success = mail($webMaster, $emailSubject, $body, $headers); EOD; $theResults = <<<EOD <html> <head> <meta http-equiv="refresh" content="3;//media-ondemand.com"> <title>Sent Message</title> <style type="text/css"> <!-- body { text-align: center; font-family: Verdana, Geneva, sans-serif; font-size: 36px; font-weight: bold; font-variant: normal; color: #666; } --> </style> </head> <body> <p>Thank You</p> <p> Your Message Has Been Sent </p> </body> </html> EOD; echo "$theResults"; ?> the contact page is at www.media-ondemand.com/contact.html Hi all, I wrote a download script for some protected files a little while back. And on the whole, its works pretty well but occasionally, zip files will not completely download and will end up corrupted. It happens more with bigger files but that i'm guessing is due to the fact it takes longer to download them? I've searched intensively on Google for the past few days and implemented a few new ideas, which hasn't made a difference. Its annoying, in the fact you can try the same file a few times over and it'll download 8 out of 10 times no problem. I even added in the apachesentenv after a recommendation, as the rest of my site is gzip php'd. But that hasn't worked either. Part of the code as follows: apache_setenv('no-gzip', '1'); // if file exists and user access granted: // define the path to your download folder plus assign the file name $path .= $filename; // check that file exists and is readable if (file_exists($path) && is_readable($path)) { // get the file size and send the http headers $size = filesize($path); // required for IE, otherwise Content-disposition is ignored if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off'); //content type switch(strtolower(substr(strrchr($filename,'.'),1))) { case "pdf": $mime="application/pdf"; break; case "mp3": $mime="audio/x-mp3"; break; case "zip": $mime="application/zip"; break; case "rar": $mime="application/zip"; break; case "tar": $mime="application/zip"; break; case "sit": $mime="application/zip"; break; case "doc": $mime="application/msword"; break; case "xls": $mime="application/vnd.ms-excel"; break; case "ppt": $mime="application/vnd.ms-powerpoint"; break; case "gif": $mime="image/gif"; break; case "png": $mime="image/png"; break; case "jpeg":$mime="image/jpg"; break; case "jpg": $mime="image/jpg"; break; default: $mime="application/force-download"; } header("Cache-Control: public"); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Description: File Transfer"); header("Content-Type: " .$mime); header("Content-Disposition: attachment; filename=\"{$filename}\""); header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . filesize($path)); readfile("$path"); if($logging == 1){ $status = "Granted"; include('logit.php'); } exit; } Live http Headers in Firefox displays the following upon clicking a download: http://www.website.com/filedownload.php?file=12 GET /filedownload.php?file=12 HTTP/1.1 Host: www.website.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 ( .NET CLR 3.5.30729) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-gb,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Connection: keep-alive Referer: http://www.website.com/downloads.php Cookie: __utma=100661891.2064943237.1286446219.1290502952.1290505322.70; __utmz=100661891.1290502952.69.8.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=lighthouse%20cjpro; __utmc=100661891; __utmb=100661891.43.10.1290505322; PHPSESSID=8aadcc17930b9e146f103f180f30f470 HTTP/1.1 200 OK Date: Tue, 23 Nov 2010 11:22:13 GMT Server: Apache/2.2.14 (Unix) mod_ssl/2.2.14 OpenSSL/0.9.8e-fips-rhel5 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 PHP/5.2.12 X-Powered-By: PHP/5.2.12 Expires: 0 Cache-Control: must-revalidate, post-check=0, pre-check=0 Pragma: public Content-Description: File Transfer Content-Disposition: attachment; filename="Version_5_Software.zip" Content-Transfer-Encoding: binary Content-Length: 62654423 Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Content-Type: application/zip ---------------------------------------------------------- Are my headers wrong? or in the incorrect order? If not, any ideas? I'm a bit stumped! Thanks for taking the time to read my query. Hi All, Are there any decent PHP graph solutions out there? I have an SQL statement that returns 12 numberical values in an array (mssql_fetch_array). I would like to plot these values on a graph. Thanks Matt hi guys ..I want to create graphs in php. Data will be taken by mysql ofcourse... I have seen lots of options like fusion chart xml, phpgraphlib and so on... my question is What will be the best library or tool. What will be your recommendation to create graphs. Thanks
Hello All, function convertTimeFormat($time12Hour) { // Initialized required variable to an empty string. $time24Hour = ""; // Used explode() function to break the string into an array and stored its value in $Split variable. $Split = explode(":",$time12Hour); // print_r(explode (":", $time12Hour)); => Array ( [0] => 09 [1] => 50 [2] => 08AM ) // Retrieved only "hour" from the array and stored in $Hour variable. $Hour = $Split[0]; $Split[2] = substr($Split[2],0,2); // Used stripos() function to find the position of the first occurrence of a string inside another string. if($Hour == '12' && strpos($time12Hour,"AM")!== FALSE) { // Code here } elseif(strpos($time12Hour,"PM")!== FALSE && $Hour != "12") { // code here } return $time24Hour; } $time12Hour = "09:50:08AM"; $result = convertTimeFormat($time12Hour); print_r($result); /* Input : "09:50:08AM"; Output : "21:50:08PM"; */
I'm working on PHP Math for my assignment, and it requires a graph to show the functions. But, i have no idea how to build a x-y-z (3D) graph.... All codes that i have search only for 2-dimensional (x-y axis) only.. Is there any help or solutions to make a 3-dimensional graph using PHP or Javascript? thank you before Hi everyone, Newish to PHP and I'm sure this is a simple thing but I was hoping someone could help me out. I have a php file that draws a graph for me (it takes in the coordinates from a text file). What I want to do is insert a red line at the top of the graph (not from start to finish, but starting at a certain point in the graph and finishing at another point). This php code achieves the line I would like to insert into the graph: <?php $canvas = imagecreatetruecolor(1000, 10); // Allocate colors $red = imagecolorallocate($canvas, 255, 0, 0); ImageFilledRectangle($canvas, 0, 0, 1000, 10, $red); // Output and free from memory header('Content-Type: image/jpeg'); imagejpeg($canvas); imagedestroy($canvas); ?> I need to insert this into this php script: <?php $width = 1000; //width and height of the resulting image $height = 230; $drawLastLine = false; //draw 9th line or not $testMode = false; //render only 10 images //returns directory with cached images by name of text file function getCacheDirectory($fname) { $mod = filemtime($fname); $dirname = "cache/" . $fname . "." . $mod . "/"; return $dirname; } //checks if specified txt file is cached function isCached($fname) { $dirname = getCacheDirectory($fname); return file_exists($dirname); } //calculated y-coordinates of base-lines for all 9 lines, returns an array function initStart($height, $number = 9) { $d = $number + 1; $t = $height / $d; $res = array(); $c = 0; for ($i = 0; $i < $number; $i++) { $c += $t; $res[$i] = $c; } return $res; } //draws vertical grey line with specified coordinate function drawVerticalLine($img, $x) { $grey = imagecolorallocate($img, 80, 80, 80); $h = imagesy($img); imagesetthickness($img, 3); imageline($img, $x, 0, $x, $h, $grey); imagesetthickness($img, 0.1); } //cuts unfilled part of image in the right, making its width equal to $realW function cutRight($img, $realW) { $h = imagesy($img); $new = imagecreatetruecolor($realW, $h); imagecopy($new, $img, 0, 0, 0, 0, $realW, $h); return $new; } //makes up an array of required colors function allocateColors($img) { $result = array(); $result['blue'] = imagecolorallocate($img, 0, 0, 255); $result['red'] = imagecolorallocate($img, 255, 0, 0); $result['black'] = imagecolorallocate($img, 0, 0, 0); $result['white'] = imagecolorallocate($img, 255, 255, 241); return $result; } //main function which generates all the images function generateImages($fname) { set_time_limit(0); //there's no time limit, because it's long process global $width, $height, $start, $testMode, $drawLastLine; $lines = 9; $start = initStart($height, $drawLastLine ? $lines : $lines - 1); //colors of line from top bo bottom $lineCol = array('blue', 'blue', 'red', 'red', 'blue', 'blue', 'black', 'red', 'red'); $fp = fopen($fname, "r"); //we open our file with data $header = fgets($fp); $curX = 0; $sumX = 0; $imgNum = 1; $colors = false; $const = 1.0; //that's the constant which can be used to multiply by y-coordinates, i.e. making our graphs scalable by y-coordinate $prevY = array(); for ($i = 0; $i < $lines; $i++) { $prevY[$i] = 0; } $dir = getCacheDirectory($fname); mkdir($dir); $img = false; // $maximumImages = 10; //if we are testing, we will do just 10 images, else we will work until the file ends while ((!$testMode || ($testMode && $imgNum < $maximumImages)) && $line = fgets($fp)) { //if it's time to make up a new image if ($sumX % $width == 0) { //we save old one to file if ($img) { imagegif($img, $dir . $imgNum . ".gif"); $imgNum++; } //and create a new one, along with allocating colors and so on $img = imagecreatetruecolor($width, $height); $colors = allocateColors($img); imagefill($img, 0, 0, $colors['white']); $curX = 0; } $data = explode(",", $line); $time = array_shift($data); $linesCount = $drawLastLine ? $lines : $lines - 1; //we loop through our lines for ($i = 0; $i < $linesCount; $i++) { $ly = $data[$i] * $const; //it's the new Y coordinate, and we counts from baseline with y = 0 $realTo = $start[$i] + $ly; //now we count the baseline too $realFrom = $start[$i] + $prevY[$i]; //that's the previous step's y-coordinate $prevY[$i] = $ly; //we remember current coordinate to draw line on next step $x1 = $curX - 1; $y1 = $realFrom; $x2 = $curX; $y2 = $realTo; //we draw line finally with needed color imageline($img, $x1, $y1, $x2, $y2, $colors[$lineCol[$i]]); } //if the time looks like 235.000000, we need to draw vertical line if (round($time) == $time) { drawVerticalLine($img, $curX); } //we increase both curX (which is used for drawing) and overall x (it indicates how much lines we've processed) $curX++; $sumX++; } // if we didn't save all lines to .gifs, we need to save leftovers if ($curX > 0) { $img = cutRight($img, $curX); imagegif($img, $dir . $imgNum . ".gif"); $imgNum++; } //saving numbers of pictures rendered file_put_contents($dir . "info.txt", ($imgNum - 1)); } $fname = $_GET['file']; //there should be no slashes in filename and it should end with .txt if (strpos($fname, "/") !== false || strpos($fname, "\\") !== false || strpos($fname, ".txt") === false) { echo "Security error!"; die; } //it should exist if (!file_exists($fname)) { echo "No such file!"; die; } //if there are no images cached for our file, we need to generate them if (!isCached($fname)) { generateImages($fname); } $page = 1; $dirname = getCacheDirectory($fname); $maxPages = file_get_contents($dirname . "info.txt"); //$maxPages = 10; $uniqid = uniqid(); $img = $dirname . $page . ".gif?" . uniqid(); include("templates/show2.php.inc"); I'm just lost as to how I achive this line in the longer php script. I've tried creating my own function, and then calling it further down but this just breaks it. Any help is appreciated!! Hello, I found this great free php calandar script here "" by Xu and Alessandro, and I'm trying to modify the code to mark several dates(birthdays YYYY-mm-dd) from a date column in a sql database. I've played around with the _showDay() method but I can't seem to get it working.. I've also tried to create a _showBirthday() method to modify the css as well but with no luck. What I'm trying to do is loop through the database to mark the respective dates on the calendar, and have a href to display a new page with the person's name when I click the specific date. Can anyone help with this. Thanks in advance! I need a simple line graph for my PHP site showing page views against date (monthly). Have tried to find plugins but can't find an appropriate one. Can someone please help with a script or direct me to a plugin. Attached is the kind of graph I'd like to have. Following Sams PHP 24hrs... Rewrote Example and it isn't working... I am not getting any syntax error just an error saying it cannot display the graph because there are errors in the image. I have went through it line for line looking for mispellings you name it making sure it was exactly as they wrote so I could follow along... but now its is not working and I believe its me.. not the book... can anyone help me out? <?php //Send content type header to browser so image will be rendered header ("Content-type: image/png"); class SimpleBar { private $xgutter = 20;//left/right margin private $ygutter = 20;//top/bottom margin private $bottomspace = 30;//gap at the bottom private $internalgap = 10;//gap between bars private $cells = array();//labels/amounts for bar charts private $totalwidth; private $totalheight; private $font; function __construct( $width, $height, $font ) { $this->totalwidth = $width; $this->totalheight = $height; $this->font = $font; } //Used to allow user to populate $cells[] property array function addBar( $label, $amount ) { $this->cells[ $label ] = $amount; } private function _getTextSize( $cellwidth ) { $textsize = (int)( $this->bottomspace );//Make $textsize equal to bottomspace if ( $cellwidth < 10 ) { $cellwidth = 10; } //Loop through the cells array and acquire dimension info for the labels using imageTTfbBox() foreach ( $this->cells as $key=>$val ) { while ( true ) { $box = imageTTFbBox( $textsize, 0, $this->font, $key ); $textwidth = abs ( $box[2] ); if ( $textwidth < $cellwidth ) { break; } $textsize--; } } return $textsize; } function draw() { $image = imagecreate( $this->totalwidth, $this->totalheight );//Create Image Resource //Create Color resources $red = imagecolorallocate( $image, 255,0,0 );//Red $blue = imagecolorallocate( $image, 0,0,255 );//Blue $black = imagecolorallocate( $image, 0,0,0 );//Black $max = max( $this->cells );//Cache the maxium value the $cells[] array has $total = count( $this->cells );//Cache the number of elements the $cells[] array contains $graphCanX = ( $this->totalwidth - $this->xgutter*2 );//Set up the canvas space on the X-axis for the graph $graphCanY = ( $this->totalheight - $this->ygutter*2 - $this->bottomspace );//Set up the canvas space on the Y-axis for the graph ( Have to allow room for our labels and margins ) $posX = $this->xgutter;//Store the starting point for drawing our bars on the X-axis $posY = $this->totalheight - $this->ygutter; - $this->bottomspace;//Store the starting point for drawing our bars on the Y-axis ( Have to allow room for our labels and margins ) $cellwidth = (int) ( ( $graphCanX -( $this->internalgap * ( $total - 1 ) ) ) / $total );//Calculate the cellwidth for each bar by taking the width of the graph canvas and subtracting the total distance bewteen the bars divided by the total amount of bars being used $textsize = $this->_getTextSize( $cellwidth ); foreach( $this->cells as $key=>$val ) { $cellheight = (int) ( ( $val/$max ) * $graphCanY );//Calculate height of each bars $center = (int) ( $posX + ($cellwidth/2) );//Calculate cener point of bars $imagefilledrectangle( $image, $posX, ($posY - $cellheight), ($posX+$cellwidth), $posY, $blue);//Draw the bars $box = imageTTFbBox( $textsize, 0, $this->font, $key ); $tw = $box[2]; imageTTFtext( $image, $textsize, 0, ($center-($tw/2) ), ( $this->totalheight-$this->ygutter), $black, $this->font, $key ); $posX += ( $cellwidth + $this->internalgap); } imagepng( $image ); } } $graph = new SimpleBar( 500, 300, "league_gothic-webfont.ttf" ); $graph->addBar("Really Liked" , 200); $graph->addBar("Liked" , 100); $graph->addBar("Kinda Like" , 300); $graph->draw(); ?> Anyone can help me with plotting of multiple line graph in php. I have researched on multiple line graph online and I would like to plot the graph by taking data from my database but the example below is inserting the graph data manually. Anyone can teach me how to use a for loop inside an array? Code: [Select] <?php //Include the code require_once 'phplot.php'; //Define the object $plot = new PHPlot(800,600); //Set titles $plot->SetTitle("A 3-Line Plot\nMade with PHPlot"); $plot->SetXTitle('X Data'); $plot->SetYTitle('Y Data'); //Define some data $example_data = array( array('a',3,4,2), array('b',5,3,1), array('c',7,2,6), array('d',8,1,4), array('e',2,4,6), array('f',6,4,5), array('g',7,2,3) ); $plot->SetDataValues($example_data); //Turn off X axis ticks and labels because they get in the way: $plot->SetXTickLabelPos('none'); $plot->SetXTickPos('none'); //Draw it $plot->DrawGraph(); ?> I'm trying to get a bar graph from total number of hit on a month to month basis. Everything works out find, except the bar graph is only showing 1 month, not everything that's being pulled out of the db. Can anybody look and see what I'm doing wrong? Code: [Select] $userid = '44'; $t_month = date("Y-m-d h:i:s"); $y_month = date("Y-m-d h:i:s", strtotime("-1 Year")); //Grabs Unique Visitors to App Page $query = "SELECT CONCAT_WS(' ', YEAR(date), MONTHNAME(date)) AS RptDate, COUNT(DISTINCT referrer) 'referrer' FROM app_analytics WHERE appid = $userid AND date BETWEEN '" .$y_month."' AND '" .$t_month."' GROUP BY CONCAT_WS(' ', YEAR(date), MONTHNAME(date)) ORDER BY YEAR(date), MONTH(date)"; $result = mysql_query($query) or die(mysql_error()); //$totals = array(); while($row = mysql_fetch_array( $result )){ $months = date("M", strtotime($row['RptDate'])); $ip = $row['referrer']; $values = array("$months" => $ip); $img_width=450; $img_height=300; $margins=20; # ---- Find the size of graph by substracting the size of borders $graph_width=$img_width - $margins * 2; $graph_height=$img_height - $margins * 2; $img=imagecreate($img_width,$img_height); $bar_width=20; $total_bars=count($values); $gap= ($graph_width- $total_bars * $bar_width ) / ($total_bars +1); # ------- Define Colors ---------------- $bar_color=imagecolorallocate($img,0,64,128); $background_color=imagecolorallocate($img,240,240,255); $border_color=imagecolorallocate($img,200,200,200); $line_color=imagecolorallocate($img,220,220,220); # ------ Create the border around the graph ------ imagefilledrectangle($img,1,1,$img_width-2,$img_height-2,$border_color); imagefilledrectangle($img,$margins,$margins,$img_width-1-$margins,$img_height-1-$margins,$background_color); # ------- Max value is required to adjust the scale ------- $max_value=max($values); $ratio= $graph_height/$max_value; # -------- Create scale and draw horizontal lines -------- $horizontal_lines=20; $horizontal_gap=$graph_height/$horizontal_lines; for($i=1;$i<=$horizontal_lines;$i++){ $y=$img_height - $margins - $horizontal_gap * $i ; imageline($img,$margins,$y,$img_width-$margins,$y,$line_color); $v=intval($horizontal_gap * $i /$ratio); imagestring($img,0,5,$y-5,$v,$bar_color); } # ----------- Draw the bars here ------ for($i=0;$i< $total_bars; $i++){ # ------ Extract key and value pair from the current pointer position list($key,$value)=each($values); $x1= $margins + $gap + $i * ($gap+$bar_width) ; $x2= $x1 + $bar_width; $y1=$margins +$graph_height- intval($value * $ratio) ; $y2=$img_height-$margins; imagestring($img,0,$x1+3,$y1-10,$value,$bar_color); imagestring($img,0,$x1+3,$img_height-15,$key,$bar_color); imagefilledrectangle($img,$x1,$y1,$x2,$y2,$bar_color); } header("Content-type:image/png"); imagepng($img); } Thanks in advance Hi all, I am currently making a website that has e-custom functions and a back end for the client. I want them to be able to upload images - but they need to be transparent. I do not want to leave this in the hands of the client, so I am looking at ways of using the GD library to make the change I got no issue with the png/gif type for upload/resize function since this type already transparent background but my major problems is how to deal with jpeg/jpg image type which is their background was not a transparent...so is it possible I can change/ convert to png/gif type upon successful of uploading image...so the new final image will be png/gif type with transparent background...is it doable...I am not even sure it is possible...? Thanks for any help.. |