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

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
Steve TinsleyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
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.
Steve TinsleyAuthor 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 EngineerCommented:
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
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

Pravin AsarPrincipal Systems EngineerCommented:
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

Julian HansenCommented:
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.
Slick812Commented:
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 ?

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.