PHP - Php Variables In Google Chart
Hello,
Newbie needs some help pls. Searched far and wide, seen others ask but no answer (maybe too obvious).
I have a simple function to do some basic math (its for young children)
<?php for($i=0;$i<$_POST['period'];$i++):
$year=$current_year+$i;
Similar TutorialsHi I'm using a the following google Pie Cart from here http://code.google.com/apis/ajax/playground/#pie_chart I would like to use php to COUNT printers listed in a column called machine and return result so I can echo it into google code Example of Column below would return a count of one for each except for the TurboJet which would return two. I would then like to echo the results to the google Javascript for printer 1 to 6. _______ machine ________ FB7500-1 TurboJet XL1500-1 Roland Canon TurboJet Can anyone help? Cheers Chris Code: [Select] <?php mysql_connect("localhost","chris","Cr2baxKUHWGxr6nn"); @mysql_select_db("schedule") or die( "Unable to select database"); date_default_timezone_set('Europe/London'); $query = "SELECT machine, COUNT(machine) FROM maindata GROUP BY machine"; $result = mysql_query($query) or die(mysql_error()); // Print out result while($row = mysql_fetch_array($result)){ echo "There are is ". $row['COUNT(machine)'] ." ". $row['machine'] ." items."; echo "<br />"; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title> Google Visualization API Sample </title> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('visualization', '1', {packages: ['corechart']}); </script> <script type="text/javascript"> function drawVisualization() { // Create and populate the data table. var data = new google.visualization.DataTable(); data.addColumn('string', 'Task'); data.addColumn('number', 'Hours per Day'); data.addRows(5); data.setValue(0, 0, 'Printer 1'); data.setValue(0, 1, 11); data.setValue(1, 0, 'Printer 2'); data.setValue(1, 1, 2); data.setValue(2, 0, 'Printer 4'); data.setValue(2, 1, 2); data.setValue(3, 0, 'Printer 5'); data.setValue(3, 1, 2); data.setValue(4, 0, 'Printer 6'); data.setValue(4, 1, 7); // Create and draw the visualization. new google.visualization.PieChart(document.getElementById('visualization')). draw(data, {title:"Current Work in Progress"}); } google.setOnLoadCallback(drawVisualization); </script> </head> <body style="font-family: Arial;border: 0 none;"> <div id="visualization" style="width: 600px; height: 400px;"></div> </body> </html> Good afternoon,
I am working on a project that gives the user a data table and a google chart (using the api) based on what the user selects for a <select> <option>.
Index.PHP code:
<form> <select name="users" onchange="showUser(this.value);drawChart();"> <option value=""> Select a Metal: </option> <?php //connection details $query = "SELECT TOP(31) tblMetalPrice.MetalSourceID, tblMetalSource.MetalSourceName from tblMetalPrice INNER JOIN tblMetalSource ON tblMetalPrice.MetalSourceID=tblMetalSource.MetalSourceID ORDER BY tblMetalPrice.DateCreated DESC "; $result = sqlsrv_query( $conn, $query); while( $row = sqlsrv_fetch_object ($result)) { echo "<option value='".$row->MetalSourceID ."'>". $row->MetalSourceName ."</option>"; } sqlsrv_close( $conn); ?> </select> </form> <div id="chart_div"></div> <div id="txtHint"><b>Past metal information will be generated below.</b></div>this works fine and generates the list in the select option dropdown Script to get table contents: <script> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","scripts/gettabledata001.php?q="+str,true); xmlhttp.send(); } </script>this also works fine and generates the table contents based on 'q' value from the select dropdown. Google API script: <script type="text/javascript"> // Load the Visualization API and the piechart,table package. google.load('visualization', '1', {'packages':['corechart']}); google.setOnLoadCallback(drawChart()); function drawChart() { var jsonData = $.ajax({ url: "scripts/getgraphdata.php", dataType:"json", data: "q="+num, async: false }).responseText; // Instantiate and draw our pie chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, {width: 400, height: 240}); } </script>getgraphdata.php script: $q = intval($_GET['q']); ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(-1); $query ="SELECT TOP(30) tblMetalPrice.MetalSourceID, tblMetalPrice.DateCreated, tblMetalPrice.UnitPrice, tblMetalPrice.HighUnitPrice, tblMetalSource.MetalSourceName FROM tblMetalPrice INNER JOIN tblMetalSource ON tblMetalPrice.MetalSourceID = tblMetalSource.MetalSourceID WHERE tblMetalPrice.MetalSourceID = '".$q."' ORDER BY tblMetalPrice.DateCreated DESC"; $result = sqlsrv_query($conn, $query); echo "{ \"cols\": [ {\"id\":\"\",\"label\":\"Date\",\"pattern\":\"\",\"type\":\"string\"}, {\"id\":\"\",\"label\":\"Unit Price\",\"pattern\":\"\",\"type\":\"number\"} ], \"rows\": [ "; $total_rows = sqlsrv_num_rows($result); $row_num = 0; while($row = sqlsrv_fetch_object($result)){ $row_num++; if ($row_num == $total_rows){ echo "{\"c\":[{\"v\":\"" . $row->DateCreated->format('d-m-Y') ."\",\"f\":null},{\"v\":" . $row->UnitPrice . ",\"f\":null}]}"; } else { echo "{\"c\":[{\"v\":\"" . $row->DateCreated->format('d-m-Y') ."\",\"f\":null},{\"v\":" . $row->UnitPrice . ",\"f\":null}]}, "; } } echo " ] }"; sqlsrv_close( $conn);When ever i try these they don't work the getgraphdata.php scripts runs fine the issue I believe but may be totally wrong may be done to the google api script that should generate the chart but doesn't. Can anyone help here I've been trying to sort this for a few days now and losing confidence in myself rapidly. Thanks Kris I recently created a site that creates charts with google charts api and information it collects from a database that the owner of the site inputs. All works well except for the left and right axis top numbers. These display odd top numbers and I am wondering what it would take to get it to round the number up to the nearest 100 so that it displays evenly. I set the code to go 100 over and I think that somewhere in here is my problem. If a user inputs a number of 255 and that number is the highest within the chart data then the top number displays 355. It displays both top number 255 and 355. Now what this does is makes the gains look higher that they actually are because it goes from 200, 255 and then 355. Please see example out put here I am sure there must be away to dynamically add the axis labels without it pulling in the info from the data itself right? I have asked this very same question on google code and still know answer. Here is an example of the code I am using. <?php $id_entity = $_product->getId(); $chart_num_rows = 0; $db_obj = mysql_connect('localhost', 'XXX', 'XXX'); mysql_select_db('XXXX', $db_obj); $query = " SELECT a.frontend_label AS frontend_label, b.value AS value FROM XXX AS a, XXX AS b WHERE a.attribute_id = b.attribute_id && b.entity_id = ".$id_entity." && a.attribute_id BETWEEN 564 AND 568 ORDER BY a.attribute_id ASC "; $result = mysql_query($query); if(mysql_num_rows($result) != 0) { @$chart_num_rows = mysql_num_rows($result); } if($chart_num_rows != 0) { $max = 0; $min = 0; $array = array(); for($i = 0; $i < $chart_num_rows; $i++) { $row = mysql_fetch_object($result); $clean = str_replace(" ", '', $row->value); $explode = explode(',', $clean); if($i == 4) { $min = min($explode); $max = max($explode); } else { if($min < min($explode)) { $min = min($explode); } if($max < max($explode)) { $min = max($explode); } } $array[$i][0] = $row->frontend_label; /* Labels */ $array[$i][1] = $clean; /* Line Data */ $array[$i][2] = str_replace(',', '|', $clean); /* Labels */ } $count = 100; $left_right = ''; while($count < $max) { $left_right .= $count.'|'; $count = ($count + 100); } $left_right .= $max.'|'.($max + 100); $output = '<img src="http://chart.apis.google.com/chart? cht=lc&chd=t:'.$array[1][1].'|'.$array[2][1].'|'.$array[3][1].'|'. $array[4][1]; $output .= '&chls=3|3|3|3|3|3,6,3&chf=bg,s,FFFFFF&chxl=0:|'.$array[0] [2].'|1:|'.$left_right.'|2:|'.$left_right; $output .= '&chs=575x300&chf=bg,s,FFFFFF&chco=444444,444444,0000FF, 0000FF&chxt=x,y,r&chds=50,'.($max + 100); $output .= '&chm=h,76A4FB,0,0:1:.2,2,-1|V,76A4FB,0,::2,0.5,-1"><br / ><br />'; } else { $output = 'There are no current statistics available for this chart.'; } echo $output; ?> Following on from my problem with another Google Chart which jay0316 kindly helped with, I have another issue which I am hoping that someone might be able to help me with.
I am trying to put together a site for my wife to manage her diabetes and insulin intake. We want to monitor her blood/sugar glucose over periods of time (but with notes that she includes that can help monitor reasons for outlying results such as illness), so I am trying to include a Google Annotation Chart to do this, drawing on blood/glucose readings stored in a Database.
Where I am struggling at the moment is converting timestamps into information that I can include in the chart.
What I currently have at the moment (which obviously isn't working) is:
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['annotationchart']}]}"></script> <script type='text/javascript'> google.load('visualization', '1', {'packages':['annotationchart']}); google.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('datetime', 'Date'); data.addColumn('number', 'Readings'); data.addColumn('string', 'Notes'); data.addRows([ <?php$annotate=DB::getInstance()->query("SELECT * FROM tabbyhealth WHERE reading!=0"); <?php $url = "myurl"; $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_URL, $url); $getdata = curl_exec($curl); $data = json_decode($getdata); $users = $data->result[0]->Users; $datapoints = array(); foreach($users as $user): $dataPoints[] = array( 'label' => $user->UserObject->UserName, 'y' => $user->Amount); endforeach; echo "<pre>"; print_r($dataPoints); echo "</pre>"; echo json_encode($dataPoints, JSON_FORCE_OBJECT); ?> <!DOCTYPE HTML> <div class="container"> <h2>Chart.js — Pie Chart Demo</h2> <div> <canvas id="myChart"></canvas> </div> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <script> var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'pie', data: { labels: "{label}", datasets: [{ backgroundColor: [ "#2ecc71", "#3498db", "#95a5a6", "#9b59b6", "#f1c40f", "#e74c3c", "#34495e" ], data: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?> }] } }); </script> <style> .container { width: 80%; margin: 15px auto; } </style> what is wrong? I can no longer see the chart. Json { "result": [ { "ID": 1, "Users": [ { "UserObject": { "UserName": "User1", "-": { "ID": 1 }, "0": "0" }, "User": "User1", "Amount": 57654456 }, { "UserObject": { "UserName": "User2", "-": { "ID": 1 }, "0": "0" }, "User": "User2", "Amount": 57654456 }, { "UserObject": { "UserName": "User3", "-": { "ID": 1 }, "0": "0" }, "User": "User3", "Amount": 57654456 } ], "Reached": false, "IsActive": true } ], "error": false, "version": 1 }
Hello, In a MySQL table I have the following rows: Item name Item price Milk 1.05 Butter 1.50 Lettuce 0.70 Butter 1.55 Bread 0.65 Chicken 3.50 Milk 1.00 Coca Cola 1.20 Apples 0.90 Toothpaste 1.00 Oranges 0.80 Milk 1.00 What I'm looking to do is collect all of the milks, all of the butters, etc and give a $total_price_spent_on value for each product, so for milk we'd have 3.05, for oranges we'd have 0.80, and so on until all items on the list have been totalled. Then I want to select the most expensive 3 totals, display them in a pie chart, and all other items to be listed under an "other" label. Any pointers as to how to go about this? Many thanks Am trying to query my DB and use the result to create a chart. code pasted below;
<?php $date = $_POST['Date']; //$date = '25/05/2010'; $date = str_replace('/', '-', $date); $new_date = date('Y-m-d', strtotime($date)); //echo $new_date; include('mysql_connect.php'); // Settings for the graph include "libchart/classes/libchart.php"; $chart = new VerticalBarChart(600, 520); $chart = new VerticalBarChart(); $dataSet = new XYDataSet(); $query1 = mysql_query ("select * from requisition where date = '$new_date' ") or die(mysql_error()); while($row = mysql_fetch_array($query1)) { //$amt = $row['amount']; // check each department and sum up all their data if ( $row['department'] = "ICT") { $total1 = $total1 + $row['amount']; //exit; } else if ( $row['department'] = "Supply Chain/ Asset Integrity") { $total2 = $total2 + $row['amount']; //exit; } else if ( $row['department'] = "Account") { $total3 = $total3 + $row['amount']; //exit; } else if ( $row['department'] = "Admin / Services ") { $total4 = $total4 + $row['amount']; //exit; } else if ( $row['department'] = "Business Development") { $total5 = $total5 + $row['amount']; //exit; } else if ( $row['department'] = "Manpower") { $total6 = $total6 + $row['amount']; //exit; } else if ( $row['department'] = "Maintenance") { $total7 = $total7 + $row['amount']; //exit; } else if ( $row['department'] = "HR") { $total8 = $total8 + $row['amount']; //exit; } else if ( $row['department'] = "Marine Logistics") { $total9 = $total9 + $row['amount']; //exit; } //$dataSet->addPoint(new Point($row['department'], $row['amount'])); } $dataSet->addPoint(new Point("ICT", $total1)); $dataSet->addPoint(new Point("Supply Chain", $total2)); $dataSet->addPoint(new Point("Account", $total3)); $dataSet->addPoint(new Point("Admin / Services", $total4)); $dataSet->addPoint(new Point("Business Development", $total5)); $dataSet->addPoint(new Point("Manpower", $total6)); $dataSet->addPoint(new Point("Maintenance", $total7)); $dataSet->addPoint(new Point("HR", $total8)); $dataSet->addPoint(new Point("Logistics", $total9)); $chart->setDataSet($dataSet); $chart->setTitle("Report By Date - $date"); $chart->render("generated/date.png"); header("Location: view_date.php"); //header ('lcoation : '); ?> ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: When i Try to view the result, it only displays the first one in the IF statement. please, what am i doing wrong? Thanks in advance This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355580.0 I wish to access the following chart by the number and the headings names. field text mysqlfield 1 username Please enter a username un 2 name Please enter you name nm 3 age Please enter your age ag 4 town What town do you live in tw 5 postcode What is your postcode pc I place the field and the text in to a form and use the mysqlfield to placce the data in the mysql database. what i do not know is how to store the array data and how to access it. I am trying to create something similar to a bar chart, using a html table based on the values stored in an array. However, I cannot seem to get the next column to begin after printing the number at the bottom. I can get it going horizontal, but I would like to create a vertical version. If anyone can provide me with help I would greatly appreciate it. Code: [Select] <?php $month = date("n"); //numeric representation of month (1-12) $year = date("Y"); //4 digit representation of year $day = date("d"); //numeric representation of the day of the month // constant variable to determine how many days alive according to the current date define('DAYS_ALIVE',(($year - 1902) * 365.24) + (($month - 1) * 30.5 )+ ($day - 1)); $divident = 100000; // variable for modulus $divider = 10000; // variable to shrink the divident for($i = 0; $i <= 4; $i++) // for loop to fill the array with days alive { $daysArray[$i]= floor((DAYS_ALIVE % $divident)/$divider); //calculates the single digit to store in array $divident= $divident/10; //after every iteration the divident is decreased $divider= $divider/10; //after every iteration the divider is decreased } echo "<table border='2' width='100%'>"; $arraySize = count($daysArray); //variable for the array size for($k=0;$k<=$arraySize-1;$k++) { echo "<tr>"; for($j=1;$j<=$daysArray[$k];$j++) { echo "<td> * </td>"; } echo "<td>$daysArray[$k]</td>"; } echo "</table>"; ?> What I want is something like this. Hi again, I have a bar chart, standard 3 verticle bars coloured differently, but now i want to put some text on them, say: Bar A, Bar B, Bar C. Also this text has to be rotated 90 degrees So here is the code to make the bars, I guess I need to use: $red = imagecolorallocate($im, 255, 0, 0); imagestring($im, 5, 50, 50, "Bar A", $red); In some kind of loop so: $text = array( imagestring($im, 5, 50, 50, "Bar A", $red); imagestring($im, 5, 50, 50, "Bar B", $red); imagestring($im, 5, 50, 50, "Bar C", $red); ); can anyone help? Code: [Select] 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; Code: [Select] //SQL connect stuff // 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); $colours = array( imagecolorallocate ($im,0xff,0x00,0xcc), imagecolorallocate ($im,0xcc,0xff,0x00), imagecolorallocate ($im,0x00,0xcc,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,$colours[$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); imagedestroy($im); ?> This question is part PHP, part MySQL. I have a survey_responses table...
- id - survey_id - question_id - member_id - response
For satisfaction questions (i.e. 1 = Strongly Disagree, 2 = Disagree, 3 = Neither, 4 = Agree, 5 = Strongly Agree), I'm trying to figure out how to get the counts for each of those responses into PHP so I can then feed them to a Bar Chart I hope to create with HTML/CSS. 1.) Should I create some kind of loop in PHP, and look for each value (e.g. 1 = Strongly Disagree) and one at a time plug them into variables called: $stronglyDisagree, $disagree, $neighter, $agree, $stronglyAgree?
2.) Or do I first need a "cross-tab" query in MySQL?
3.) Would this be easier if the database values were in a PHP array?
Not sure where to begin with this, and more importantly, I want to make sure that my data model in MySQL is sufficient so i can do reporting like this!!
Thanks.
This topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=358786.0 Hello, I'm trying to work out a method of displaying a pie chart depending on the values in an array by looping for a different value of $i, here's what I have so far: for($i = 0; $i < 11; $i++) { $colour = $i; $fraction = ($pie_data[$i]/$total); $pie_angle = $fraction*360; ImageFilledArc($myImage, 100, 100, 200, 180, STARTANGLE, ENDANGLE, $colour, IMG_ARC_PIE); } As you can see I've got fractions, which I'm converting into an angle. However, I can't think of a way to have the startangle and endangle parameters of the ImageFilledArc function depend on all of the previous pie angles, because I'm hoping this pie chart can vary as pieces of data forming each wedge (and each fraction) change. Can anybody help with this? Thanks so much for your help. Hello all,
Am trying to calculate some data and display the result of the current month in a chart form. i just don't know how to get the current month. this is not working..
<?php include('mysql_connect.php'); $date = 'MONTH(CURRENT_DATE())'; $status = 'paid'; //mysql_select_db("hyprops", $con); $query = mysql_query("SELECT sum(amount) 'amount', department FROM requisition WHERE status = '$status' AND date='$date' "); $category = array(); $category['name'] = 'department'; //$series1 = array(); //$series1['name'] = 'actual'; $series2 = array(); $series2['name'] = 'amount'; //$series3 = array(); //$series3['name'] = 'Highcharts'; while($r = mysql_fetch_array($query)) { $category['data'][] = $r['department']; // $series1['data'][] = $r['actual']; $series2['data'][] = $r['amount']; // $series3['data'][] = $r['highcharts']; } $result = array(); array_push($result,$category); //array_push($result,$series1); array_push($result,$series2); //array_push($result,$series3); print json_encode($result, JSON_NUMERIC_CHECK); mysql_close($con); ?>Please how can i solve this issue? Thanks in advance Hi Freaks, I am trying to make a gantt chart with data stored in a mysql database but I am having problems with the syntax. I can create the chart ok by hard coding, and I can see the database query is returning the expected data, but I just can't quite figure the correct syntax to pass the data to jpgraph to get the result. simplified code: Code: [Select] <?php require_once('connections/manager.php'); ?> <?php mysql_select_db($database_manager, $manager); $query_project = "SELECT `task`, `dateStart`, `dateFinish`, `managerName` FROM `test`"; $project = mysql_query($query_project, $manager) or die(mysql_error()); $row_project = mysql_fetch_assoc($project); $totalRows_project = mysql_num_rows($project); require_once ('jpgraph/jpgraph.php'); require_once ('jpgraph/jpgraph_gantt.php'); $graph = new GanttGraph(800); $graph->title->Set("Project"); $graph->ShowHeaders(GANTT_HYEAR | GANTT_HMONTH | GANTT_HDAY | GANTT_HWEEK); $graph->scale->day->SetStyle(DAYSTYLE_SHORTDATE4); $graph->scale->day->grid->Show(); $graph->scale->month->SetStyle(MONTHSTYLE_LONGNAME); $graph->scale->week->SetFont(FF_FONT1); $n=0; do { $data[]=array(array($n,$row_project["task"],$row_project["dateStart"],$row_project["dateFinish"],$row_project["managerName"])); ++$n; //echo "\$bar".$n." = new GanttBar(".$n.",\"".$row_project["task"]."\",\"".$row_project["dateStart"]."\",\"".$row_project["dateFinish"]."\",\"".$row_project["managerName"]."\")"; }while ($row_project=mysql_fetch_array($project)); $graph->Add(array($data)); // I figure this is where I'm going wrong? $graph->Stroke(); mysql_free_result($project); ?> This is giving me the following error: Quote Fatal error: Call to a member function GetMaxDate() on a non-object in jpgraph/jpgraph_gantt.php on line 630 Other variations bring up an error graphic saying no date value, so as I said I'm pretty sure it's a problem with passing the array to jpgraph... There don't appear to be any forums at jpgraph, and other searching isn't giving me any joy so any pointers would be most welcome. I am using the pChart (http://www.pchart.net/) PHP class framework to create a pie chart using database values which I have extracted using this select query:
$query = "SELECT Labels, COUNT(quantity) as quantity FROM inventory GROUP BY Labels"; $result = $mysqli->query($query); /* associative array */ while($row = $result->fetch_assoc()) { $titles = (array_values($row)); $count = $row['quantity']; $Labels = $row['Labels']; print_r($count); print_r($Labels); }The implementation procedure for the pChart framework requires two array data sources as shown in code sample below: The absissa series, and ordinate series /* Create and populate the pData object */ $MyData = new pData(); $MyData->addPoints(array(40,60,15,10,6,4,80),"quantity"); $MyData->setSerieDescription("quantity","Application A"); /* Define the absissa series */ $MyData->addPoints(array("Table","Chair","Bed","Stove","Lamp","Rug", "Others"),"Labels"); $MyData->setAbscissa("Labels");Within this context, how may I get the absissa and ordinate values as arrays into the pChart for creations of the pie chart? Thanks Help please.. 50yr old PHP noob.. I have a PHP script that runs a personality survey and returns the dominant personality type, but I need to display the results as a bar chart reflecting the % totals for each of the 4 personality types. Code is he http://codepad.org/wQN3qN3v Grateful for any help! does anyone know how to decode this XML variable value into string values? I also need to know the oposite way: creating variable values into xml. I've tried several code examples but they did filter the requested data. Code: [Select] $xml='<?xml version="1.0" encoding="utf-8"?> <elements> <text identifier="ed9cdd4c-ae8b-4ecb-bca7-e12a5153bc02"> <value/> </text> <textarea identifier="a77f06fc-1561-453c-a429-8dd05cdc29f5"> <value><![CDATA[<p style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>]]></value> </textarea> <textarea identifier="1a85a7a6-2aba-4480-925b-6b97d311ee6c"> <value><![CDATA[<p style="text-align: justify;">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>]]></value> </textarea> <image identifier="ffcc1c50-8dbd-4115-b463-b43bdcd44a57"> <file><![CDATA[images/stories/red/cars/autobedrijf.png]]></file> <title/> <link/> <target/> <rel/> <lightbox_image/> <width><![CDATA[250]]></width> <height><![CDATA[187]]></height> </image> <text identifier="4339a108-f907-4661-9aab-d6f3f00e736e"> <value><![CDATA[Kramer 5]]></value> </text> <text identifier="ea0666d7-51e3-4e52-8617-25e3ad61f8b8"> <value><![CDATA[6000 RS]]></value> </text> <text identifier="90a18889-884b-4d53-a302-4e6e4595efa0"> <value><![CDATA[Eindhoven]]></value> </text> <text identifier="410d72e0-29b3-4a92-b7d7-f01e828b1586"> <value><![CDATA[APK Pick up and return]]></value> </text> <text identifier="45b86f23-e656-4a81-bb8f-84e5ea76f71f"> <value><![CDATA[15% korting op grote beurt]]></value> </text> <text identifier="3dbbe1c6-15d6-4375-9f2f-f0e7287e29f3"> <value><![CDATA[Gratis opslag zomerbanden]]></value> </text> <text identifier="2e878db0-605d-4d58-9806-8e75bced67a4"> <value><![CDATA[Gratis abonnement of grote beurt]]></value> </text> <text identifier="94e3e08f-e008-487b-9cbd-25d108a9705e"> <value/> </text> <text identifier="73e74b73-f509-4de7-91cf-e919d14bdb0b"> <value/> </text> <text identifier="b870164b-fe78-45b0-b840-8ebceb9b9cb6"> <value><![CDATA[040 123 45 67]]></value> </text> <text identifier="8a91aab2-7862-4a04-bd28-07f1ff4acce5"> <value/> </text> <email identifier="3f15b5e4-0dea-4114-a870-1106b85248de"> <value/> <text/> <subject/> <body/> </email> <link identifier="0b3d983e-b2fa-4728-afa0-a0b640fa34dc"> <value/> <text/> <target/> <custom_title/> <rel/> </link> <relateditems identifier="7056f1d2-5253-40b6-8efd-d289b10a8c69"/> <rating identifier="cf6dd846-5774-47aa-8ca7-c1623c06e130"> <votes><![CDATA[1]]></votes> <value><![CDATA[1.0000]]></value> </rating> <googlemaps identifier="160bd40a-3e0e-48de-b6cd-56cdcc9db892"> <location><![CDATA[50.895711,5.955427]]></location> </googlemaps> </elements>'; Hi, I found a couple of topics in the search on this but can't resolve my problem. I have a cart and want to mail it to myself and the client. The cart I'm using works fine but the moment I "check out" (mail the order) it gives a error. I build an error trap but see nothing wrong then I tried a different way to send the order in html with no avail. 6x files I use: Index.php -The products I'm selling and "add to chart" Cart.php - To update and display the products in the basket SendOrder.php - To mail the cart etc. to me and client as the main files and some functions, db connection and global's... 1) Index.php by Simon Mayer <?php // Start the session session_start(); // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>MedSET Store</title> <link rel="stylesheet" href="css/styles.css" > </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Products</h1> <?php $sql = 'SELECT * FROM books ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': £'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); ?> </div> </body> </html> 2)Cart.php by Simon Mayer <?php // Start the session session_start(); // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Process actions $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'add': if ($cart) { $cart .= ','.$_GET['id']; } else { $cart = $_GET['id']; } break; case 'delete': if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $newcart; } break; case 'update': if ($cart) { $newcart = ''; foreach ($_POST as $key=>$value) { if (stristr($key,'qty')) { $id = str_replace('qty','',$key); $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($id != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } for ($i=1;$i<=$value;$i++) { if ($newcart != '') { $newcart .= ','.$id; } else { $newcart = $id; } } } } } $cart = $newcart; break; } $_SESSION['cart'] = $cart; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>MedSET Store</title> <link rel="stylesheet" href="css/styles.css" > </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="contents"> <h1>Please check quantities...</h1> <?php echo showCart(); ?> <form action="sendOrder.php" method="post"> //I added the action file to handle the form <input type="submit" name="sendmail" value="Check Out" > </form> <p><a href="index.php">Continue Shopping...</a></p> </div> </body> </html> 2.1)MySQL.class.php <?php /** * MySQL Database Connection Class * @access public * @package SPLIB */ class MySQL { /** * MySQL server hostname * @access private * @var string */ var $host; /** * MySQL username * @access private * @var string */ var $dbUser; /** * MySQL user's password * @access private * @var string */ var $dbPass; /** * Name of database to use * @access private * @var string */ var $dbName; /** * MySQL Resource link identifier stored here * @access private * @var string */ var $dbConn; /** * Stores error messages for connection errors * @access private * @var string */ var $connectError; /** * MySQL constructor * @param string host (MySQL server hostname) * @param string dbUser (MySQL User Name) * @param string dbPass (MySQL User Password) * @param string dbName (Database to select) * @access public */ function MySQL ($host,$dbUser,$dbPass,$dbName) { $this->host=$host; $this->dbUser=$dbUser; $this->dbPass=$dbPass; $this->dbName=$dbName; $this->connectToDb(); } /** * Establishes connection to MySQL and selects a database * @return void * @access private */ function connectToDb () { // Make connection to MySQL server if (!$this->dbConn = @mysql_connect($this->host, $this->dbUser, $this->dbPass)) { trigger_error('Could not connect to server'); $this->connectError=true; // Select database } else if ( !@mysql_select_db($this->dbName,$this->dbConn) ) { trigger_error('Could not select database'); $this->connectError=true; } } /** * Checks for MySQL errors * @return boolean * @access public */ function isError () { if ( $this->connectError ) return true; $error=mysql_error ($this->dbConn); if ( empty ($error) ) return false; else return true; } /** * Returns an instance of MySQLResult to fetch rows with * @param $sql string the database query to run * @return MySQLResult * @access public */ function query($sql) { if (!$queryResource=mysql_query($sql,$this->dbConn)) trigger_error ('Query failed: '.mysql_error($this->dbConn). ' SQL: '.$sql); return new MySQLResult($this,$queryResource); } } /** * MySQLResult Data Fetching Class * @access public * @package SPLIB */ class MySQLResult { /** * Instance of MySQL providing database connection * @access private * @var MySQL */ var $mysql; /** * Query resource * @access private * @var resource */ var $query; /** * MySQLResult constructor * @param object mysql (instance of MySQL class) * @param resource query (MySQL query resource) * @access public */ function MySQLResult(& $mysql,$query) { $this->mysql=& $mysql; $this->query=$query; } /** * Fetches a row from the result * @return array * @access public */ function fetch () { if ( $row=mysql_fetch_array($this->query,MYSQL_ASSOC) ) { return $row; } else if ( $this->size() > 0 ) { mysql_data_seek($this->query,0); return false; } else { return false; } } /** * Returns the number of rows selected * @return int * @access public */ function size () { return mysql_num_rows($this->query); } /** * Returns the ID of the last row inserted * @return int * @access public */ function insertID () { return mysql_insert_id($this->mysql->dbConn); } /** * Checks for MySQL errors * @return boolean * @access public */ function isError () { return $this->mysql->isError(); } } ?> 2.2)Global.inc.php <?php $host = 'localhost'; $user = 'MyUserName'; $pass = 'MyPassword'; $name = 'MyDataBase'; $db = &new MySQL($host,$user,$pass,$name); ?> 2.3)Function.inc.php <?php function writeShoppingCart() { $cart = $_SESSION['cart']; if (!$cart) { return '<p>You have no items in your shopping cart</p>'; } else { // Parse the cart session variable $items = explode(',',$cart); $s = (count($items) > 1) ? 's':''; return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>'; } } function showCart() { global $db; $cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; } $output[] = '<form action="cart.php?action=update" method="post" id="cart">'; $output[] = '<table>'; foreach ($contents as $id=>$qty) { $sql = 'SELECT * FROM books WHERE id = '.$id; $result = $db->query($sql); $row = $result->fetch(); extract($row); $output[] = '<tr>'; $output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>'; $output[] = '<td>'.$title.' by '.$author.'</td>'; $output[] = '<td>£'.$price.'</td>'; $output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>'; $output[] = '<td>£'.($price * $qty).'</td>'; $total += $price * $qty; $output[] = '</tr>'; } $output[] = '</table>'; $output[] = '<p>Grand total: <strong>£'.$total.'</strong></p>'; $output[] = '<div><button type="submit">Update cart</button></div>'; $output[] = '</form>'; } else { $output[] = '<p>You shopping cart is empty.</p>'; } return join('',$output); } ?> 3)SendOrder.php <?php $cart = $_SESSION['cart']; $to = "me@myself.com"; $subject = "MedSET Order"; $message = "<html> <head> <title>Email Order<Title> </head> <body> This is my message in body </body>"; $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; $headers .= 'From: "email address" <an email existing on same server as shopping cart>' . "\r\n"; mail($to, $subject,$message,$headers,$cart); ?> Any help will be appreciated... |