Create javascript array from php sql query for use with charts.js

Steve Tinsley
Steve Tinsley used Ask the Experts™
on
I am using http://www.chartjs.org/ to create some bar charts. The data is coming from a php / sql query.

I need to get the php data into the js arrays but im not sure how.

This is as far as I have got:

<script type="text/javascript">
<?php foreach ($rows as $row) {
	extract($row); ?>
	console.log('<?= $questionOption; ?>');
	console.log('<?= $questionResponseCount; ?>');
<?php } ?>


$( document ).ready(function() {

	//EXAMPLE DATA
	var barData = {
		labels : ["January","February","March","April","May","June"],
		datasets : [
			{
				data : [203,156,99,251,305,247]
			}
		]
	}


    var canvas = document.getElementById('canvas').getContext('2d');
    new Chart(canvas).Bar(barData);
});
</script>

Open in new window


I hope you can help.

Steve
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Have you tried

echo "var data = " . json_encode($rows .';');

Open in new window


This might not work because the JSON structure that is output might not match what you are expecting in your JavaScript code in which case you might have to massage your PHP data.

What does your data look like in $rows - can you var_dump / print_r it so we can have a look.

Author

Commented:
This is what I get returned:

Array ( [0] => Array ( [questionOptionID] => 60 [questionID] => 29 [questionOption] => Queen Mary [correctAnswer] => 1 [questionResponseCount] => 6 ) [1] => Array ( [questionOptionID] => 61 [questionID] => 29 [questionOption] => Queen Boudica [correctAnswer] => 0 [questionResponseCount] => 36 ) [2] => Array ( [questionOptionID] => 62 [questionID] => 29 [questionOption] => Queen Matilda [correctAnswer] => 0 [questionResponseCount] => 8 ) [3] => Array ( [questionOptionID] => 63 [questionID] => 29 [questionOption] => Queen Elizabeth I [correctAnswer] => 0 [questionResponseCount] => 3 ) )

Open in new window


and I need questionOption and questionResponseCount.
Pravin AsarPrincipal Systems Engineer
Top Expert 2005

Commented:
Here is a example for you,
<?php
$months=array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
$datasets = array(
  "dataset"=> array(
    array("data" => array (10,110,210,310,410,510), 
      "label" => "My First dataset",
      "fillColor"=> "rgba(220,220,220,0.5)",
      "strokeColor"=> "rgba(220,220,220,0.8)",
      "highlightFill"=> "rgba(220,220,220,0.75)",
      "highlightStroke"=> "rgba(220,220,220,1)"),  
    array("data" => array (20,120,220,320,420,520),
      "label"=> "My Second dataset",
      "fillColor"=> "rgba(220,220,220,0.5)",
      "strokeColor"=> "rgba(220,220,220,0.8)",
      "highlightFill"=> "rgba(220,220,220,0.75)",
      "highlightStroke"=> "rgba(220,220,220,1)"),  
    array("data" => array (30,130,230,330,430,530),
      "label"=> "My Third dataset",
      "fillColor"=> "rgba(220,220,220,0.5)",
      "strokeColor"=> "rgba(220,220,220,0.8)",
      "highlightFill"=> "rgba(220,220,220,0.75)",
      "highlightStroke"=> "rgba(220,220,220,1)")
    )
);

$jsonArray = array("months"=> $months, "datasets"=> $datasets);
echo json_encode($jsonArray,JSON_PRETTY_PRINT);
?>

Open in new window

You have to pick appropriate sql query/data columns for each data values
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Pravin AsarPrincipal Systems Engineer
Top Expert 2005

Commented:
Here is an another example, showing how to build array and then output the json

            
$mydata = array(
  array("questionOptionID" => 10, "questionID" => 19,"questionOption" => "Question Option 1", "correctAnswer" => 1,"questionResponseCount" => 6),
  array("questionOptionID" => 20, "questionID" => 29,"questionOption" => "Question Option 2", "correctAnswer" => 1,"questionResponseCount" => 10),
  array("questionOptionID" => 30, "questionID" => 39,"questionOption" => "Question Option 3", "correctAnswer" => 2,"questionResponseCount" => 30),
  array("questionOptionID" => 40, "questionID" => 49,"questionOption" => "Question Option 4", "correctAnswer" => 3,"questionResponseCount" => 100),
  array("questionOptionID" => 50, "questionID" => 59,"questionOption" => "Question Option 5", "correctAnswer" => 3,"questionResponseCount" => 20)
);

echo json_encode($mydata,JSON_PRETTY_PRINT);

$qdata1 = array();
$qdata2 = array();

foreach ($mydata as $qdata) {
  echo "<h3>" .  $qdata['questionOption'] . ":" . $qdata['questionResponseCount'] .  "</h3>";
  array_push($qdata1,$qdata['questionOption']);
  array_push($qdata2,$qdata['questionResponseCount']);
}

$jsonArray = array(
  "labels"=> $qdata1, 
  "datasets"=> array(
  "data"=>$qdata2,
  "label"=> "My Third dataset",
  "fillColor"=> "rgba(220,220,220,0.5)",
  "strokeColor"=> "rgba(220,220,220,0.8)",
  "highlightFill"=> "rgba(220,220,220,0.75)",
  "highlightStroke"=> "rgba(220,220,220,1)")
);

echo json_encode($jsonArray,JSON_PRETTY_PRINT);

Open in new window

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Firstly, not sure how the data dump you posted ties into Chart.js - did you dump the correct data? The data looks like a question structure for a survey type application.

Here is some sample code for how to get the Array data you posted into a JavaScript array - you can adapt if necessary
<!doctype html>
<html>
<body>
<?php
$rows = array ( 
array ( 
	'questionOptionID' => 60,
	'questionID' => 29, 
	'questionOption' => "Queen Mary", 
	'correctAnswer' => 1, 
	'questionResponseCount' => 6
	), 
array ( 
	'questionOptionID' => 61,
	'questionID' => 29, 
	'questionOption' => "Queen Boudica",
	'correctAnswer' => 0, 
	'questionResponseCount' => 36 
),
array ( 
	'questionOptionID' => 62, 
	'questionID' => 29, 
	'questionOption' => "Queen Matilda",
	'correctAnswer' => 0, 
	'questionResponseCount' => 8 
), 
array ( 
	'questionOptionID' => 63, 
	'questionID' => 29, 
	'questionOption' => "Queen Elizabeth I", 
	'correctAnswer' => 0, 
	'questionResponseCount' => 3 
	) 
);
$json = json_encode($rows);
echo $json;
echo <<< JSCRIPT
<script>
	var questions={$json};
</script>
JSCRIPT;
?>
<script>
console.log(questions);
</script>
</body>
</html>

Open in new window

Working sample here. Examine the console to see the output of the console.log(questions) that dumps the JavaScript array created by the PHP script.
greetings  sjtinsley83 , , please notice that in Javascript you can define an Array as a comma delimited expression (NOT a string) like in your code -
        203,156,99,251,305,247

I looked at your data in the DB return, and It looks like you will need to build TWO PHP strings for your chart output, the first string with be the lables of the chart bars from the DB questionOption like -
      "Queen Mary","Queen Boudica","Queen Matilda","Queen Elizabeth I"

and the bar heights from DB questionResponseCount as
     6,36,8,3

<?php 
$labels = "";
$bars = "";
foreach ($rows as $row) {
    extract($row); // get the variable separations
    $labels .= '"'.$questionOption.'",'; // build the lables with " and ,
    $bars .= $questionResponseCount.','; // build the bars with just a ,
  }
// chop off the last ,
$labels = substr($labels, 0, -1);
$bars = substr(bars, 0, -1);
?>

$( document ).ready(function() {

	//EXAMPLE DATA
	var barData = {
		labels : [<?php echo $labels; ?>],
		datasets : [
			{
				data : [<?php echo $bars; ?>]
			}
		]
	}


    var canvas = document.getElementById('canvas').getContext('2d');
    new Chart(canvas).Bar(barData);
});
</script>

Open in new window

some like this may can work ?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial