PHP: How to pass multiple variables to an array? - php

In the google chart api, the data for the chart is set by this line:
data.addRows([
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 860, 580],
['2007', 1030, 540]
]);
I want to be able to set this data from data in my database. Below is an image of my database:
I want to take all values of salePrice and unitPrice and display the values on a line chart that corresponds to the period they were created.
Here is my code:
<?php
include("getteam.php");
$saleprice = mysql_query("
SELECT `outputValue` FROM `output` WHERE `teamID` = '$teamID' && `outputType` = 'salePrice'
")or die($saleprice."<br/><br/>".mysql_error());
// set ID's = to a variable and now get Outputs for each variable(teamID)
$salepriceNumR = mysql_num_rows($saleprice);
$sPrice = array();
$i="0";
while ($i<$salepriceNumR && $row = mysql_fetch_assoc($saleprice))
{
$sPrice[$i] = $row['outputValue'];
$i++;
}
$unitprice = mysql_query("
SELECT `outputValue` FROM `output` WHERE `teamID` = '$teamID' && `outputType` = 'unitPrice'
")or die($unitprice."<br/><br/>".mysql_error());
// set ID's = to a variable and now get Outputs for each variable(teamID)
$unitpriceNumR = mysql_num_rows($unitprice);
$uPrice = array();
$i="0";
while ($i<$unitpriceNumR && $row = mysql_fetch_assoc($unitprice))
{
$uPrice[$i] = $row['outputValue'];
$i++;
}
$chartrow = array();
for ($i = 0; $i < $unitpriceNumR; $i++ )
{
$chartrow[$i] = "['".$i."',".$sPrice[$i].", ".$uPrice[$i]."]";
}
switch ($currentStage) {
case "0":
case "1":
$value = $chartrow[0];
break;
case "2":
$value = $chartrow[0].",".$chartrow[1];
break;
case "3":
$value = $chartrow[0].",".$chartrow[1].",".$chartrow[2];
break;
default:
$value = $chartrow[0];
// You should have some default value, seriously!!!
}
?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows(JSON.parse( [<?php echo json_encode($value); ?>] ));
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
The problem is the way I am setting $value it is a string and so the data is not outputted correctly. Is there a way I can set $value so I can use it as intended?
When $value is echoed ($currentStage being the value 3) this is outputted:
['0',0, 0],['1',65, 35],['2',88, 35]
However when I view source I am getting:
data.addRows(JSON.parse( ["['0',0, 0],['1',65, 35],['2',88, 35]"] ));
I need to get rid of the "".

You have to parse your JSON string :
data.addRows(JSON.parse( <?php echo json_encode($value); ?> ));
If I'm not mistaken that should solve your problem.
Edit In fact I'm not sure I understand why you're setting you $value variable to a string; the whole point of json_encode being that you can directly encode objects or arrays.
Edit 2 : Here's how I see it, but my php is more than rusty.
<?php
$chartrow = array();
for ($i = 0; $i < $unitpriceNumR; $i++ )
{
$chartrow[$i] = array( (string)$i, (int)$sPrice[$i], (int)$uPrice[$i] );
}
switch ($currentStage) {
case "0":
case "1":
$value = $chartrow[0];
break;
case "2":
$value = array($chartrow[0], $chartrow[1]);
break;
case "3":
$value = array($chartrow[0], $chartrow[1], $chartrow[2]);
break;
default:
$value = $chartrow[0];
}
Edit 3 I edited the js snippet, I don't know why I left the brackets around the php tags.
Edit 4 Edited the php code to the working version.

Related

display ajax information under input field

I tried to develop an ajax to display some information.
My ajax works fine but it do not display the information under the input field.
Do you have any idea to resolve that ?
thank you.
$content .= HTML::inputField('suppliers_id', $suppliers_id . ' ' . $suppliers_name, 'id="ajax_suppliers_id" list="supplier_list" class="form-control"', null, null, null);
$content .= '<datalist id="supplier_list"></datalist>';
$suppliers_ajax = this->link('ajax/suppliers.php');
<script>
window.addEventListener("load", function(){
// Add a keyup event listener to our input element
document.getElementById('ajax_suppliers_id').addEventListener("keyup", function(event){hinter(event)});
// create one global XHR object
// so we can abort old requests when a new one is make
window.hinterXHR = new XMLHttpRequest();
});
// Autocomplete for form
function hinter(event) {
var input = event.target;
var ajax_suppliers_id = document.getElementById('ajax_suppliers_id');
// minimum number of characters before we start to generate suggestions
var min_characters = 0;
if (!isNaN(input.value) || input.value.length < min_characters ) {
return;
} else {
window.hinterXHR.abort();
window.hinterXHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse( this.responseText );
ajax_suppliers_id.innerHTML = "";
response.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
option.value = item;
ajax_suppliers_id.appendChild(option);
});
}
};
window.hinterXHR.open("GET", "{$suppliers_ajax}?q=" + input.value, true);
window.hinterXHR.send()
}
}
</script>
my ajax request called across the input field, I use to display information:
if (isset($_GET['q'])) {
$terms = HTML::sanitize(strtolower($_GET['q']));
$Qcheck = $this->Db->prepare('select distinct suppliers_id as id,
suppliers_name as name
from :table_suppliers
where suppliers_name LIKE :terms
limit 10;
');
$Qcheck->bindValue(':terms', '%' . $terms . '%');
$Qcheck->execute();
$list = $Qcheck->rowCount();
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch()) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
}
example of response I can see on sa keywords:
[{"id":"3","name":"Samsug"}]
You are appending new options inside input but you need to append it inside datalist .Also , option.value = item.name will give you result has [Object object] that's why you need to specify field i.e : id ,name to access same elements . i.e : item.name .
Demo Code :
var ajax_suppliers_id = document.getElementById('supplier_list');//daatlist id
var response = [{
"id": "3",
"name": "Samsug"
},{
"id": "3",
"name": "Samsug1"
},{
"id": "3",
"name": "Samsug2"
}];
ajax_suppliers_id.innerHTML = "";
response.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
option.value = item.name;//get name
ajax_suppliers_id.appendChild(option);
});
<input list="supplier_list" class="form-control" id="ajax_suppliers_id">
<datalist id="supplier_list"></datalist>

Google visualization world map

I'm trying to retrieve results using json in order to display world map with country list.
This is what I got so far:
function drawRegionsMap() {
$.ajax({
url: 'getlist.php",
dataType: "json"
}).done(function(result) {
var data = google.visualization.arrayToDataTable(result);
var view = new google.visualization.DataView(data)
view.setColumns([0, 1])
var chart = new google.visualization.GeoChart(
document.getElementById('map'));
chart.draw(data, options);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
var options = {
width: "auto",
height: "auto",
colorAxis: {
colors: ['#E4B6D3', '#E06D94']
} // Map Colors
};
geochart.draw(data, options);
});
};
google.load('visualization', '1', {
'packages': ['geochart']
});
google.setOnLoadCallback(drawRegionsMap);
result returned from getlist.php is in json format:
{
"Country":[
"Germany",
"United States",
"Brazil",
"France",
"RU"
],
"Hits":[
200,
300,
400,
500,
600,
700
]
}
php code:
$data = array();
$data['Country'] = array();
$data['Hits'] = array();
$country = array('Germany','United States','Brazil','France','RU');
$hits = array(200,300,400,500,600,700);
for ($i = 0; $i < 6; $i++){
$data['Country'] = $country;
$data['Hits'] = $hits;
}
echo json_encode($data);
Looking in firebug console, I'm always getting : Error: Not an array
I've been trying to solve this puzzle for hours, but no success.
The returned result is an object, not an array.
The expected array would be:
[
["Country","Hits"],
["Germany",200],
["United States",300],
["Brazil",400],
["France",500],
["RU",600]
]
Modified PHP-code that returns this array:
<?php
$data = array(['Country','Hits']);
$country = array('Germany','United States','Brazil','France','RU');
$hits = array(200,300,400,500,600,700);
foreach ($country as $k => $v){
$data[] = array($v,$hits[$k]);
}
echo json_encode($data);
?>

Google Charts from MySQL JSON Encoded Array

I'm having one heck of a time here, how can I draw up the chart from a json_encoded mySQL array?
Data Retrieval (simply associated array from a PDO query):
if($cCt > 0){
header('Content-Type:application/json');
$table['cols'] = array(
array('id'=>'Date', 'label'=>'Date', 'type'=>'string'),
array('id'=>'Carbs', 'label'=>'Carbs', 'type'=>'number'),
array('id'=>'Sugar', 'label'=>'Sugar', 'type'=>'number'),
array('id'=>'Units', 'label'=>'Units', 'type'=>'number'));
for($i=0; $i<$cCt; ++$i){
$W = (isset($_GET['which'])) ? (int)$_GET['which'] : 0;
switch($W){
case 1: // weekly
case 2: // monthly
case 3: // yearly
$date = date('m/d', strtotime($CNums[$i]['Date']));
break;
case 4: // daily
$date = date('m/d g:i a', strtotime($CNums[$i]['Date']));
break;
default:
$date = date('m/d g:i a', strtotime($CNums[$i]['Date']));
break;
}
$rows[] = array('c'=>array('v'=>$date, 'v'=>$CNums[$i]['Carbs'], 'v'=>$CNums[$i]['Sugar'], 'v'=>$CNums[$i]['Units']));
}
$table['rows'] = $rows;
echo json_encode($table, JSON_NUMERIC_CHECK);
}else{
echo ErrorBox('Please login to see your charts.');
}
Code Attempt:
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var $dUrl = "/assets/php/charts/chart.data.php?_=<?php echo time(); ?>&which=<?php echo (isset($which)) ? $which : 4; ?>&d=<?php echo (isset($d)) ? $d : null; ?>&dl=<?php echo (isset($dl)) ? $dl : null; ?>";
jQuery.getJSON($dUrl, function(d){
// Create a new blank DataTable
var data = new google.visualization.DataTable(d);
// Create our columns
/*
data.addColumn('date', 'Date');
data.addColumn('number', 'Carbs');
data.addColumn('number', 'Sugar');
data.addColumn('number', 'Units');
// Create our Rows
jQuery.each(d, function(i) {
data.addRows([d[i].Dates, d[i].Carbs, d[i].Sugar, d[i].Units]);
});
*/
var options = {
'colors': ['red', 'blue', 'yellow'],
'width': '98%',
'height': 280,
'backgroundColor': 'none',
'hAxis': {'textStyle': {fontName: 'Calibri',
fontSize: '12'}},
'vAxis': {'textStyle': {fontName: 'Calibri',
fontSize: '12'}},
'legendTextStyle': {fontName: 'Calibri',
fontSize: '12'}
};
//var chart = new google.visualization.ColumnChart(document.getElementById('<?php echo $where; ?>'));
var chart = new google.visualization.ColumnChart(document.getElementById('weekly_chart_div'));
chart.draw(data, options);
}).fail(function(msg){console.log('Error pulling in the data.' + msg);});
}
</script>
Original JSON from the $dUrl:
{"cols":[{"id":"Date","label":"Date","type":"string"},
{"id":"Carbs","label":"Carbs","type":"string"},
{"id":"Sugar","label":"Sugar","type":"string"},
{"id":"Units","label":"Units","type":"string"}],
"rows":[["08\/23","40.0000000","256.0000000","9.0000000"],
["08\/24","33.8333333","102.5000000","4.6666667"],
["08\/25","38.2000000","290.2000000","10.6000000"],
["08\/26","36.0000000","322.0000000","12.0000000"],
["08\/28","23.6666667","348.3333333","9.6666667"],
["08\/29","31.3333333","214.1666667","7.3333333"],
["08\/30","16.0000000","154.0000000","4.0000000"]]}
New JSON after Data Retrieval Update:
{"cols":[{"id":"Date","label":"Date","type":"string"},
{"id":"Carbs","label":"Carbs","type":"number"},
{"id":"Sugar","label":"Sugar","type":"number"},
{"id":"Units","label":"Units","type":"number"}],
"rows":[{"c":{"v":9}},{"c":{"v":4.6666667}},{"c":{"v":10.6}},{"c":{"v":12}},{"c":{"v":9.6666667}},{"c":{"v":7.3333333}},{"c":{"v":4}}]}
Yes, right now I am getting an error this.J[a].c is undefined, but it only shows where the chart should be loaded...not in FireBug
What I am aiming for is something like this:
example: http://o7th.com/Image3.png
Your rows are not formatted correctly. Rows is an array of objects, where each object has a "c" (array of cells) and an optional "p" (properties object) parameters. The array of cells is an array of objects with "v" (column data type, value of cell) and optional "f" (string, formatted value of cell) and "p" (parameters object) properties.
As an example, your first row of data should look like this:
{"c":[{"v":"08\/23"},{"v":40,"f":"40.0000000"},{"v":256,"f":"256.0000000"},{"v":9,"f":"9.0000000"}]}
In order to generate that from a JSON encoded PHP array, the array would have to look like this:
$row = array(
'c' => array(
array('v' => '08\/23'),
array('v' => 40, 'f' => "40.0000000"),
array('v' => 256, 'f' => "256.0000000"),
array('v' => 9, 'f' => "9.0000000")
)
);
By default, MySQL outputs all numbers as strings, so you need to cast them as ints or floats in order for them to be output as numbers, like this:
$foo = '33.333333'; // $foo == '33.333333'
$bar = (int) $foo; // $bar == 33
$cad = (float) $foo; // $cad == 33.333333
You can change or remove the formatted values if you don't want them (they are what will appear in the tooltips of the chart).
Edit:
You need to give each cell it's own array in the cells array; try this:
$rows[] = array(
'c'=>array(
array('v'=>$date),
array('v'=>$CNums[$i]['Carbs']),
array('v'=>$CNums[$i]['Sugar']),
array('v'=>$CNums[$i]['Units'])
)
);

How to get mysql data into a google chart using php loop?

I've created a Google chart and I've added data taken from the database itself. When getting data through php loops though, I have had some difficulty because I couldn't amend that data to the chart because of its syntax.
This is as far as I have gone. I need to get the mysql values in place of: 1170, 460, 45, 123, 456],
660, 1120, 145, 785, 658]
var data = google.visualization.arrayToDataTable([
['Term', <?php
while ($getchartrows = mysql_fetch_array($getchart))
{
echo " ' " . $getchartrows['std_ID'] . " ' " . ",";
}
?>],
<?php
$one = mysql_query("SELECT * FROM stusitting WHERE std_ID = '0001' AND subjectNo = '$subin' AND grade = '$gradein' AND termNo = '$tcheck' ");
$getone = mysql_fetch_array($one);
?>
['01', <?php echo $getone ['marks']; ?>, 400, 495, 565, 415],
['02', 1170, 460, 45, 123, 456],
['03', 660, 1120, 145, 785, 658]
]);
var options = {
title: 'Class Progress'
};
Try to tackle one problem after the other. First, get the data you need from the database. Then, create the data structure you need in PHP, and convert it to JavaScript using json_encode(). Finally, pass it to the visualization function in JavaScript:
<?php
// query data
$result = mysql_query(...);
// format data structure
$data = array();
$i = 0;
while($row = mysql_fetch_array($result)) {
$i += 1;
array_push($data, array($i) + $row);
}
// convert to JavaScript
?>
var raw_data = <?php echo json_encode($data) ?>;
// visualize
var data = google.visualization.arrayToDataTable(raw_data);

How to include PHP in Javascript; Google Chart API

I am working with the google chart visualization API.
I have a variable in php:
`$value`
which contains the following:
['0',0, 0],['1',65, 35],['2',88, 35],['3',66, 35],['4',35, 35],['5',99, 100]
I want to use this $value below in data.addRows as follows however the output I am getting is blank
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Period');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
<?php echo $value ?>
]);
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
After some research it seems it is Ajax I am trying to attempt. Is this correct? Is there a simple way I can return the value $value to data.addRow??
Here is the process to which $value is set:
$i = "0";
$period = "0";
$chartrow = array();
$unitpriceNumR = 3
while ($i<3)
{
$chartrow[$i] = "['".$period."',".$sPrice[$i].", ".$uPrice[$i]."]";
$period++;
$i++;
}
switch ($currentStage)
{
case "0":
$value = $chartrow[0];
break;
case "1":
$value = $chartrow[0];
break;
case "2":
$value = $chartrow[0].",".$chartrow[1];
break;
}
In this example if $currentStage = "2" then $value is set to ['0',0, 0],['1',65, 35]
Ok now I have even tried a copy and paste of google code into my file and still no success of seeing a graph. (code taken from:http://code.google.com/intl/en-EN/apis/chart/interactive/docs/gallery/linechart.html)
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
data.addRows([
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 860, 580],
['2007', 1030, 540]
]);
var options = {
width: 400, height: 240,
title: 'Company Performance'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
Using this code
$chartrow = array();
for ($i = 0; $i < 3; $i++ )
{
$chartrow[] = array((string) $i, $sPrice[$i], $uPrice[$i]);
echo $chartrow;
}
results in $chartrow displaying the word "Array" to the screen.
Please have a look at the JSON encode function provided with PHP. This will let you echo or print out a JSON encoded string that JavaScript transforms into a native object.
$value = array(
array('0', 0, 0),
array('1', 65, 35),
array('2', 88, 35),
...
);
...
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
// Change this and the following lines to:
data.addRows(<?php print json_encode($value); ?>);
EDIT
$i = 0;
$chartrow = array();
$unitpriceNumR = 3
for (; $i < 3; $i++ )
$chartrow[] = array((string) $i, $sPrice[$i], $uPrice[$i]);
switch ($currentStage) {
case "0":
case "1":
$value = $chartrow[0];
break;
case "2":
$value = array_slice($chartrow, 0, 2);
default:
// You should have some default value, seriously!!!
}
// Then go the json_encode way, it's safer and easier to maintain!
...
data.addColumn('number', 'Sales');
data.addColumn('number', 'Expenses');
// Change this and the following lines to:
data.addRows(<?php print json_encode($value); ?>);
Change [<?php echo $value ?>] to <?php echo json_encode($value) ?>
echo $value produces Array(5) because PHP doesn't natively know how to represent an array as a string.
echo json_encode($value) produces:
[['0',0, 0],['1',65,35],['2',66,35],['4',35,35],['5',99, 100]]
so you don't need brackets around the <?php ... ?>.
http://php.net/manual/en/function.json-encode.php
EDIT: thanks for clarifying how the PHP variables are formed.
The problem is that you're manually converting arrays into strings, when you should let $json_encode do all of the work for you.
Revised version of the PHP code:
$chartrow = array();
$unitpriceNumR = 3;
for ($i=0; $i<=2; $i++)
$chart_row[$i] = array($i, $sPrice[$i], $uPrice[$i];
switch ($currentStage)
{
case '0':
case '1':
$value = $chartrow[0];
break;
case '2':
$value = array($chartrow[0], $chartrow[1]);
break;
}
EDIT2: I tried what you did (replacing the php block with what we expect the php block to produce) and it didn't work for me either. Firebug says 'Container is not defined' in Google's own code.
You forgot to add a div to your document. Add <div id='chart_div'></div> after the script.
So we're on the same page: http://jsfiddle.net/daemon/nnpeE/
Here is the answer to this problem
PHP: How to pass multiple variables to an array?
Whenever I have values like that I do this as my first script on the page and it seems to work for me. It also allows me to inspect what is going on with the PHP instead of the variable being hidden in some function. Note that this will create a global variable which might be not what you want.
<script>
var a = [<?php echo($var1) ?>];
</script>
EDIT:
I got your PHP code to work for me. The changes I made was I converted $i to just 0 not "0" The same goes for the switch statement . Also line 4 needs a semicolon after it. Then I put this
<script>
var a = [<?php echo($value) ?>];
</script>
And the output in the page was
<script>
var a = [['0',, ],['1',, ]];
</script>

Categories