PHP - Jpgraph Gantt Chart And Mysql Array
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. Similar TutorialsThis topic has been moved to Other Libraries and Frameworks. http://www.phpfreaks.com/forums/index.php?topic=358786.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 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 Hi All, I am currently using jpgraph on a site, and I'm trying to get the (x,y) coordinates an a chart to have two different colors ... (x = green, y = red) You can see an example he http://entropylinks.com/testgraph-dev.php?energy=2.2&entropy=1.75 Here is my code: Code: [Select] <?php // content="text/plain; charset=utf-8" require_once ("graph/src/jpgraph.php"); require_once ("graph/src/jpgraph_scatter.php"); DEFINE('MATRIX','images/matrix-big-2.png'); $datax = array(0,3); $datay = array(0,3); if(isset($_SESSION['counter']) && $_SESSION['counter'] > 1){ $x = 1.98; $y = 1.2; $count = $_SESSION['counter']; for($i = 0; $i < $count; $i++){ $datax[] += $_SESSION["entropy_$i"]; $datay[] += $_SESSION["energy_$i"]; } } else { $datax = explode('-', $_GET['energy']); $datay = explode('-', $_GET['entropy']); } $idx=0; function xyCallback($yval) { global $datay, $idx; return "($yval-".$datay[$idx++].")"; } $graph = new Graph(550,550); $graph->SetScale("intint",0,3,0,3); $graph->img->SetMargin(40,40,40,40); $graph->SetBackgroundImage(MATRIX,BGIMG_FILLPLOT); $graph->title->SetFont(FF_ARIAL,FS_BOLD); $graph->xaxis->SetTitle('CORPORATE ENTROPY','middle'); $graph->yaxis->SetTitle('CORPORATE ENERGY','middle'); $graph->yaxis->SetTextTickInterval(1,2); $sp1 = new ScatterPlot($datax,$datay); $sp1->mark->SetSize(10); $sp1->mark->SetFillColor("darkblue"); $sp1->mark->SetType(MARK_FILLEDCIRCLE); $sp1->value->SetMargin(17); $sp1->value->SetFormatCallback('xyCallback'); $sp1->value->SetColor("darkgreen"); $sp1->value->SetFont(FF_FONT0,FS_NORMAL); $sp1->value->Show(); $txt = new Text("Low"); // store text $txt->SetFont(FF_FONT0,FS_NORMAL); $txt->SetScalePos(0.5,0); $txt->SetColor('darkblue'); $txt->Center(50,150,75); $graph->AddText( $txt); // write to position $txt = new Text("Medium"); // store text $txt->SetFont(FF_FONT0,FS_NORMAL); $txt->SetScalePos(1.5,0); $txt->SetColor('darkblue'); $txt->Center(50,150,75); $graph->AddText( $txt); // write to position $txt = new Text("High"); // store text $txt->SetFont(FF_FONT0,FS_NORMAL); $txt->SetScalePos(2.5,0); $txt->SetColor('darkblue'); $txt->Center(50,150,75); $graph->AddText( $txt); // write to position $txt = new Text("Low"); // store text $txt->SetFont(FF_FONT0,FS_NORMAL); $txt->SetScalePos(-0.03,0.5); $txt->SetAngle(90); $txt->SetColor('darkblue'); $txt->Center(50,150,75); $graph->AddText( $txt); // write to position $txt = new Text("Medium"); // store text $txt->SetFont(FF_FONT0,FS_NORMAL); $txt->SetScalePos(-0.03,1.5); $txt->SetAngle(90); $txt->SetColor('darkblue'); $txt->Center(50,150,75); $graph->AddText( $txt); // write to position $txt = new Text("High"); // store text $txt->SetFont(FF_FONT0,FS_NORMAL); $txt->SetScalePos(-0.03,2.5); $txt->SetAngle(90); $txt->SetColor('darkblue'); $txt->Center(50,150,75); $graph->AddText( $txt); // write to position $graph->Add($sp1); $graph->Stroke(); ?> Here's the class code that controls the scatter graph Code: [Select] //=================================================== // CLASS ScatterPlot // Description: Render X and Y plots //=================================================== class ScatterPlot extends Plot { public $mark,$link; private $impuls = false; //--------------- // CONSTRUCTOR function __construct($datay,$datax=false) { if( (count($datax) != count($datay)) && is_array($datax)) { JpGraphError::RaiseL(20003);//("Scatterplot must have equal number of X and Y points."); } parent::__construct($datay,$datax); $this->mark = new PlotMark(); $this->mark->SetType(MARK_SQUARE); $this->mark->SetColor($this->color); $this->value->SetAlign('center','center'); $this->value->SetMargin(0); $this->link = new LineProperty(1,'black','solid'); $this->link->iShow = false; } //--------------- // PUBLIC METHODS function SetImpuls($f=true) { $this->impuls = $f; } function SetStem($f=true) { $this->impuls = $f; } // Combine the scatter plot points with a line function SetLinkPoints($aFlag=true,$aColor="black",$aWeight=1,$aStyle='solid') { $this->link->iShow = $aFlag; $this->link->iColor = $aColor; $this->link->iWeight = $aWeight; $this->link->iStyle = $aStyle; } function Stroke($img,$xscale,$yscale) { $ymin=$yscale->scale_abs[0]; if( $yscale->scale[0] < 0 ) $yzero=$yscale->Translate(0); else $yzero=$yscale->scale_abs[0]; $this->csimareas = ''; for( $i=0; $i<$this->numpoints; ++$i ) { // Skip null values if( $this->coords[0][$i]==='' || $this->coords[0][$i]==='-' || $this->coords[0][$i]==='x') continue; if( isset($this->coords[1]) ) $xt = $xscale->Translate($this->coords[1][$i]); else $xt = $xscale->Translate($i); $yt = $yscale->Translate($this->coords[0][$i]); if( $this->link->iShow && isset($yt_old) ) { $img->SetColor($this->link->iColor); $img->SetLineWeight($this->link->iWeight); $old = $img->SetLineStyle($this->link->iStyle); $img->StyleLine($xt_old,$yt_old,$xt,$yt); $img->SetLineStyle($old); } if( $this->impuls ) { $img->SetColor($this->color); $img->SetLineWeight($this->weight); $img->Line($xt,$yzero,$xt,$yt); } if( !empty($this->csimtargets[$i]) ) { if( !empty($this->csimwintargets[$i]) ) { $this->mark->SetCSIMTarget($this->csimtargets[$i],$this->csimwintargets[$i]); } else { $this->mark->SetCSIMTarget($this->csimtargets[$i]); } $this->mark->SetCSIMAlt($this->csimalts[$i]); } if( isset($this->coords[1]) ) { $this->mark->SetCSIMAltVal($this->coords[0][$i],$this->coords[1][$i]); } else { $this->mark->SetCSIMAltVal($this->coords[0][$i],$i); } $this->mark->Stroke($img,$xt,$yt); $this->csimareas .= $this->mark->GetCSIMAreas(); $this->value->Stroke($img,$this->coords[0][$i],$xt,$yt); $xt_old = $xt; $yt_old = $yt; } } // Framework function function Legend($aGraph) { if( $this->legend != "" ) { $aGraph->legend->Add($this->legend,$this->mark->fill_color,$this->mark,0, $this->legendcsimtarget,$this->legendcsimalt,$this->legendcsimwintarget); } } } // Class Does anyone have a solution for this? Is it even possible? Do I need to somehow modify the class to render these different colors? Feel free to ask any questions you may have, I'm 99% complete with this, but I just can't seem to change the colors of the plot labels. Thanks! How can i save array from inputs, witch is $igraci and it have 5 values, to mysql base, i tryed but in mysql it shows Array. This is form: <form action="dodaj_klan.php" method="post" > <p> <label>Naziv klana:</label> <input name="naziv" type="text" size="20%" /> <label>Web Sajt:</label> <input name="website" type="text" size="20%" /> <label>E-Mail:</label> <input name="email" type="text" size="20%" /> <br /><br /> <label>Igraci klana(5):</label> <input name="lider" type="radio" value="1" /> <input name="igraci[]" type="text" size="20%" /><br /> <input name="lider" type="radio" value="2" /> <input name="igraci[]" type="text" size="20%" /><br /> <input name="lider" type="radio" value="3" /> <input name="igraci[]" type="text" size="20%" /><br /> <input name="lider" type="radio" value="4" /> <input name="igraci[]" type="text" size="20%" /><br /> <input name="lider" type="radio" value="5" /> <input name="igraci[]" type="text" size="20%" /> <label><i>(obelezi lidera klana)</i></label> <br /><br /> <input class="button" type="submit" name="submit" value="Dodaj" /> </p> </form> Now i wonna save this igraci[] array in mysql, i tried like this but it doesn't work: $igraci = $_POST['igraci']; $query = "INSERT INTO klanovi (naziv, website, email, igraci) VALUES ('{$naziv}', '{$website}', '{$email}', '{$igraci}')"; $result = mysql_query($query, $connection); How can i do this? Thanks.. So I'm querying my database to add the results (mapID's) into a PHP array. The MySQL query I used in the below code would usually return 10 values (only 10 mapID's in the database) Code: [Select] while($data = mysql_fetch_array(mysql_query("SELECT mapID FROM maps"))){ $sqlsearchdata[] = $data['mapID']; } Instead the page takes ages to load then gives this error: Quote Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 16 bytes) It says the error begins on the first line of the above code. I'm assuming this is not the right way to add the value from the MySQL array into a normal PHP array. Can anyone help me? Hello everyone, Sorry if this has been answered but if it has I can't find it anywhere. So, from the begining then. Lets say I had a member table and in it I wanted to store what their top 3 interests are. Their$ row has all the usual things to identify them userID and password etc.. and I had a further 3 columns which were labled top3_1 top3_2 & top3_3 to put each of their interests in from a post form. If instead I wanted to store this data as a PHP Array instead (using 1 column instead of 3) is there a way to store it as readable data when you open the PHPmyadmin? At the moment all it says is array and when I call it back to the browser (say on a page where they could review and update their interests) it displays 'a' as top3_01 'r' as top3_02 and 'r' as top3_03 (in each putting what would be 'array' as it appears in the table if there were 5 results. Does anyone know what I mean? For example - If we had a form which collected the top 3 interests to put in a table called users, Code: [Select] <form action="back_to_same_page_for_processing.php" method="post" enctype="multipart/form-data"> <input name="top3_01" type="text" value="enter interest number 1 here" /> <input name="top3_02" type="text" value="enter interest number 2 here" /> <input name="top3_03" type="text" value="enter interest number 3 here" /> <input type="submit" name="update_button" value=" Save and Update! " /> </form> // If my quick code example for this form is not correct dont worry its not the point im getting at :) And they put 'bowling' in top3_01, 'running' in top3_02 and 'diving' in top3_03 and we catch that on the same page with some PHP at the top --> Code: [Select] if (isset($_POST)['update_button']) { $top3_01 = $_POST['top3_01']; // i.e, 'bowling' changing POST vars to local vars $top3_02 = $_POST['top3_02']; // i.e, 'running' $top3_03 = $_POST['top3_03']; // i.e, 'diving' With me so far? If I had a table which had 3 columns (1 for each interest) I could put something like - Code: [Select] include('connect_msql.php'); mysql_query("Select * FROM users WHERE id='$id' AND blah blah blah"); mysql_query("UPDATE users SET top3_01='$top3_01', top3_02='$top3_02', top3_03='$top3_03' WHERE id='$id'"); And hopefully if ive got it right, it will put them each in their own little column. Easy enough huh? But heres the thing, I want to put all these into an array to be stored in the 1 column (say called 'top3') and whats more have them clearly readable in PHPmyadmin and editable from there yet still be able to be called back an rendered on page when requested. Continuing the example then, assuming ive changed the table for the 'top3' column instead of individual colums, I could put something like this - Code: [Select] if (isset($_POST)['update_button']) { $top3_01 = $_POST['top3_01']; // i.e, 'bowling' changing POST vars to local vars $top3_02 = $_POST['top3_02']; // i.e, 'running' $top3_03 = $_POST['top3_03']; // i.e, 'diving' $top3_array = array($top3_01,$top3_02,$top3_03); include('connect_msql.php'); mysql_query("UPDATE members SET top3='$top3_array' WHERE id='$id' AND blah blah blah"); But it will appear in the column as 'Array' and when its called for using a query it will render the literal string. a r r in each field instead. Now I know you can use the 'serialize()' & 'unserialize()' funtcions but it makes the entry in the database practically unreadable. Is there a way to make it readable and editable without having to create a content management system? If so please let me know and I'll be your friend forever, lol, ok maybe not but I'd really appreciate the help anyways. The other thing is, If you can do this or something like it, how am I to add entries to that array to go back into the data base? I hope ive explained myself enough here, but if not say so and I'll have another go. Thanks very much people, L-PLate (P.s if I sort this out on my own ill post it all here) <?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 Hi 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> 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; 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 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 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. 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); ?> 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; ?> 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.
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 |