I have an undefined Variable problem:
Effect on this first part of code everything works my variable $ id and well defined and works fine.
The cell_id is the result of a combobox which is then transmitted as an ajax on this page and it works fine
if(isset($_GET['cellule_id']) && !empty($_GET['cellule_id'])){
include('../../../connexion.php');
$id= $_GET['cellule_id'];
$query1 = pg_query($db,'SELECT ("T_CELLULE"."IDLocationEnCoursCellule"), COUNT(*) as qte_att_m
FROM "T_STATUT", "T_STATUT_CELLULE", "T_CELLULE", "T_OF"
WHERE ("T_STATUT_CELLULE"."SNCellule")=("T_CELLULE"."SNCellule")
AND ("T_STATUT"."IDStatut")=("T_STATUT_CELLULE"."IDStatut")
AND ("T_STATUT_CELLULE"."OF")=("T_CELLULE"."OF")
AND ("T_STATUT_CELLULE"."IDProcess")=("T_CELLULE"."IDProcess")
AND ("T_CELLULE"."OF"="T_OF"."OF")
AND ("T_CELLULE"."IDProcess"="T_OF"."IDProcess")
AND ("T_CELLULE"."RebutCellule" Is Null)
AND NOT("T_CELLULE"."IDLocationEnCoursCellule" Is Null)
AND ("T_CELLULE"."FinProcess" Is Null)
AND ("T_STATUT_CELLULE"."EnCours"=True)
AND ("T_STATUT"."IDStatut") = 2
AND ("T_OF"."TypeCellule")= \''. $id. '\'
GROUP BY "IDLocationEnCoursCellule"');
But when I want to display the result of my query in a js chart using google charts the problem comes from my query which is exactly the same but this time the $ id is not defined.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['IDLocationEnCoursCellule','qte_att_m'],
<?php
$result = pg_query($db,'SELECT ("T_CELLULE"."IDLocationEnCoursCellule"), COUNT(*) as qte_att_m
FROM "T_STATUT", "T_STATUT_CELLULE", "T_CELLULE", "T_OF"
WHERE ("T_STATUT_CELLULE"."SNCellule")=("T_CELLULE"."SNCellule")
AND ("T_STATUT"."IDStatut")=("T_STATUT_CELLULE"."IDStatut")
AND ("T_STATUT_CELLULE"."OF")=("T_CELLULE"."OF")
AND ("T_STATUT_CELLULE"."IDProcess")=("T_CELLULE"."IDProcess")
AND ("T_CELLULE"."OF"="T_OF"."OF")
AND ("T_CELLULE"."IDProcess"="T_OF"."IDProcess")
AND ("T_CELLULE"."RebutCellule" Is Null)
AND NOT("T_CELLULE"."IDLocationEnCoursCellule" Is Null)
AND ("T_CELLULE"."FinProcess" Is Null)
AND ("T_STATUT_CELLULE"."EnCours"=True)
AND ("T_STATUT"."IDStatut") = 2
AND ("T_OF"."TypeCellule")= \''. $id. '\'
GROUP BY "IDLocationEnCoursCellule"');
while($row = pg_fetch_assoc($result)){
echo "['".$row['IDLocationEnCoursCellule']."',".$row['qte_att_m']."],";
}
?>
]);
var options = {
chart: {
title: 'test graphique',
subtitle: 'sous titre du test graphique',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
<div id="columnchart_material"></div>
If I replace my $ id variable with a hard element it works but I have an undefined variable error
I tried a multitude of things:
- to put the $id= $_GET['cellule_id'];in the php just before my request
I've been there for 7 days on it
I can't figure out how a variable can be defined 30 lines above and then undefined thereafter.
thank you in advance good week everyone
leo
Related
I am trying to output the contents of two arrays as the axis for a chart using Google's chart API.
I currently output the JavaScript function using PHP, which is where I feel the error is. I believe the script is just getting output but not running. I can see it has output in the correct format from the page source, however, no data is being shown on the window.
The following is the contents of my two arrays, which are just key and value pairs in separate arrays:
The following is my code in the HTML body, which I call in PHP in the same page:
<?php
function createChart($nutrientArr, $percentArr) {
$chart = "<script type='text/javascript'>
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Nutrient');
data.addColumn('number', 'Percentage Intake');
data.addRows(JSON.parse([";
for($i = 0;$i < count($nutrientArr);$i++) {
$chart .= "['" . $nutrientArr[$i] . "', '" . $percentArr[$i] . "'],";
if($i == count($nutrientArr) - 1) {
$chart .= "['" . $nutrientArr[$i] . "', '" . $percentArr[$i] . "']";
}
}
$chart .= "]));
// Set chart options
var options = {'title':'Daily Nutrient Intake (Percentage)',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>";
echo $chart;
}
?>
This is the source code:
<script type='text/javascript'>
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Nutrient');
data.addColumn('number', 'Percentage Intake');
data.addRows(JSON.parse([['Calories', '18.32768'],['Fat', '23.065360824742'],['Saturated Fat', '22.640580645161'],['Monosaturated Fat', '25.274138888889'],['Polyunsaturated Fat', '23.481666666667'],['Carbohydrates', '8.6173573573574'],['Fiber', '17.975466666667'],['Sugar', '13.857878787879'],['Protein', '63.232972972973'],['Cholesterol', '37.102'],['Sodium', '7.8765666666667'],['Calcium', '13.39272'],['Magnesium', '20.481214285714'],['Potassium', '17.816553191489'],['Iron', '52.980375'],['Zinc', '25.689818181818'],['Phosphorus', '51.941142857143'],['Vitamin A', '13.804971428571'],['Vitamin C', '15.494555555556'],['Thiamin (B1)', '21.825333333333'],['Riboflavin (B2)', '23.152538461538'],['Niacin (B3)', '69.055'],['Vitamin B6', '63.236153846154'],['Folate Equivalent (Total)', '40.9758'],['Folate (Food)', '19.098075'],['Folic Acid', '0.8311225'],['Vitamin B12', '24.940875'],['Vitamin D', '2.1734733333333'],['Vitamin E', '13.491866666667'],['Vitamin K', '18.9045']]));
// Set chart options
var options = {'title':'Daily Nutrient Intake (Percentage)',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
I call the createChart() function in PHP at the top of the page, passing the two arrays.
I am looking to see what the best method of passing this data to the chart API is? Should I call the JS function from PHP and pass the arrays that way? I am not too familiar with JS so not sure how I would pass this data. Any help is very appreciated!
I have tried using json_encode and json_parse but neither work as I suspect I'm outputting the code at the wrong time or wrong way.
I knew the answer was going to be much simpler then I was making it out to be. I added the following if statement to the while loop.
<?php
echo "['Month', '$year1' , '$year2' , '$currentYear'],";
require('./PHPConnect.php');
$statement1 = #mysqli_query($dbc, $query1);
while($row = mysqli_fetch_array($statement1)){
if($row["Year3"] == NULL ? $row["Year3"] = 'null' : $row["Year3"] = $row["Year3"]);
echo "['".$row["Month"]."', ".$row["Year1"].", ".$row["Year2"].", ".$row["Year3"]."],";
}
mysqli_close($dbc);
?>
As an update we now know that the problem is MySql spits out NULL and javascript requires null. Any thoughts on how to accomplish getting MySql NULL int value into lowercase null.
*I was wondering if anyone can help me with this. I created a line chart to visual show company sales by month for the current year and the previous 2. It works fine, but because at this point there is 0 sales for the remaining months of the year it shows a steep drop off for that line. We don't want to see that, so I tried changing the 0s to nulls in the database and using interpolateNulls false. However when I add the interpolateNulls option the line chart breaks and no longer displays anything. Any ideas?
<script type="text/javascript">
var data;
var chart;
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
data = google.visualization.arrayToDataTable([
<?php
echo "['Month', '$year1' , '$year2' , '$currentYear'],";
require('./PHPConnect.php');
$statement1 = #mysqli_query($dbc, $query1);
while($row = mysqli_fetch_array($statement1)){
echo "['".$row["Month"]."', ".$row["Year1"].", ".$row["Year2"].", ".$row["Year3"]."],";
}
mysqli_close($dbc);
?>
]);
var options = {
backgroundColor: 'transparent',
title:'Total Sales By Month',
width:600,
height:500,
interpolateNulls: false,
legend: {position: 'bottom'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I've looked at other questions similar to what I am asking however they are not what I need/trying to substitute the answer into my code.
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Stock Price', 'Date'],
//['2014', 3000],
<?php
$DataSearchSQL = "SELECT * FROM stocklog WHERE status = 1 ORDER BY ID DESC LIMIT 7";
$DataSearchResult = mysqli_query($dbconfig,$DataSearchSQL);
while($DataSearchRow=mysqli_fetch_array($DataSearchResult,MYSQLI_ASSOC)) {
$data = $DataSearchRow["StockPrice"];
$timestamp = $DataSearchRow["Time"];
$splitTimeStamp = explode(" ",$timestamp);
$date = $splitTimeStamp[0];
$info = "['{$date}', {$data}]";
echo json_encode($info);
}
?>
]);
I believe I am messing something up with $info and json_encode however I am not sure what to do, help is much appreciated.
I'm trying to create a range area chart using CanvasJS and PHP to load the data from a database.
I've created the php and it returns the values from the DB.
Here is the php:
<?php
header('Content-Type: application/json');
$con = mysqli_connect("127.0.0.1","root","pwd1","db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "select (CalYear+1) as CalYear, concat('[',REPLACE(Year1PercWC,',','.'),',',REPLACE(Year1PercBC,',','.'),']') as ResultSet, concat('Sessies: ',calyear) as Help FROM table where cat='1' and (CalYear+1)<year(now())");
while($row = mysqli_fetch_array($result))
{
$point = array("x" => $row['CalYear'] , "y" => $row['ResultSet'],"name" => $row['Help']);
array_push($data_points, $point);
}
echo json_encode($data_points);
}
mysqli_close($con);
?>
With the results:
[{"x":"2007","y":"[35.94,35.94]","name":"Sessies: 2006"},{"x":"2008","y":"[27.67,27.67]","name":"Sessies: 2007"},...,...]
The problem are the quotes in the x and y values (=string values). CanvasJS only takes numbers to create a graph. So the output should be like:
[{"x":2007,"y":[35.94,35.94],"name":"Sessies 2006"},{"x":2008,"y":[27.67,27.67],"name":"Sessies 2007"},...,...]
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="jquery.canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("TestGraf.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
axisX: {
intervalType: "number",
title: "Year",
interval: 1,
valueFormatString: "#"
},
data: [
{
type: "rangeArea",
dataPoints: result
[{"x":2007,"y":[35.94,35.94],"name":"Sessies 2006"},{"x":2008,"y":[27.67,27.67],"name":"Sessies 2007"}] -- This is working fine
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
I'm sure there must be a way to adapt my php so that x and y are passed through as numbers instead of strings, but i'm really new at php (first time ever) and can't find the solution,especially for the second part (y).
Can anyone tell me which adaptions to make to the php and/or html file?
Thx,
This should probably work for you :
json_encode($arr, JSON_NUMERIC_CHECK);
It's probably a little too late for my answer but like Alex answered, you should use echo json_encode($data_points, JSON_NUMERIC_CHECK);
The numeric check is an option. See http://php.net/manual/en/json.constants.php
However, more understanding of how a range area chart works seems to be the problem. The range area chart has an X and 2 Y values. The 2 Y values are needed to plot the range. If you simply go to the testgraf.php file in your browser, your JSON result should be:
[{x: somevalue, y:[low_value, high_value]}]
You might have to change your sql statement to get another y value. You can do what you want with that. Anyway, this is what you should do for your php code:
Change
$point = array("x" => $row['CalYear'] , "y" => $row['ResultSet'],"name" => $row['Help']);
to:
$point = array("x" => $row['CalYear'] , "y" => $row['ResultSet', 'some_value'],"name" => $row['Help']);
If your 2 Y values don't change, you may not see a graph line diplayed. Would a line graph be more appropriate?
After some trial and error I found the following solution:
$result1 = mysqli_query($con, "select (CalYear+1) as CalYear, Year1PercWC, Year1PercBC, calyear as Help FROM table_2 where cat='1' and (CalYear+1)<year(now())");
while($row = mysqli_fetch_array($result1))
{
$point = array("x" => floatval($row['CalYear']),"y" => array(floatval($row['Year1PercWC']),floatval($row['Year1PercBC'])),"name" => floatval($row['Help']));
array_push($data_points, $point);
}
echo json_encode($data_points);
The problem was I needed to create an array for my Y-values in the array for the datapoints. In this array I could store the 2 values I needed for the graph.
After this was done I needed to transform al the numeric values to float_val so that the quotes around the values disappeared.
Thx for the help everyone :)
I'd like to retrieve data from database (mongodb) and with those data i'd like to draw à pie chart using google charts. in a first case i have a collection called user and each user has a boolean attribute called (paid), i'd like to count how many paid users and free users and basing on those results i will draw a pie chart with the percentage of each kind of users
this my try i tried with for a long time but i'dont arrive to show the chart,
thanks :)
<?php
$connection = new MongoClient();
$collection = $connection->pato->user;
$cursor = $collection->find();
$cursor = $collection->find(array("paid"=>true));
$x=$cursor->count();
$cursor = $collection->find(array("paid"=>false));
$y=$cursor->count();
$myurl[]="['Option','Value']";
$myurl[]=[['Free users', $y],['Paid users', $x]];
?>
<html>
<head>
<!--Load the AJAX API-->
<body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data=google.visualization.arrayToDataTable([
<?echo(implode(",",$myurl));?>
]);
// Set chart options
var options = {'title':'User statistics',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart(document.getElementById('userStatsDiv'));
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}</script>
<body>
<div id="usageStatsDiv" style="width:700; height:500"></div>
</body>
</html>
I think your problem is with your JSON:
var data=google.visualization.arrayToDataTable([
<?echo(implode(",",$myurl));?>
]);
It looks like you're trying to build the JSON string yourself. Let PHP do the work for you instead - use json_encode instead, like this:
var data=google.visualization.arrayToDataTable([
<?php echo json_encode($data); ?>
]);
You'll need to build your $data array so that it gives you the correct elements, but I think you'll find that the end result is cleaner and easier to understand.