1

I'm trying to fetch data from DB for a line graph using the below code.

    <?php
        $dataPoints = array( 

            $sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
            $result1 = $conn->query($sql1);
            if ($result1->num_rows > 0) {                               
            while($row1 = $result1->fetch_assoc()) { 

         array("y" => 25, "label" => "Sunday"), ?>

             } } else { } 
      );
    ?>
<script>
 window.onload = function () {

   var chart = new CanvasJS.Chart("chartContainer", {
  title: {
  text: ""
      },
  axisY: {
  title: ""
      },
   data: [{
type: "line",
   dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
   }]
   });
  chart.render();
 }
</script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
         <div id="chartContainer" style="height: 370px; width: 100%;"></div>

Using the above code it gives as error as Un-expected Syntax error, expecting ) instead of ; at $dataPoints line

However if i m to remove the sql query, graph plots with static data perfectly.

Any Help is greatly appreciated..

2 Answers 2

1

I have to commend you for keeping PHP code and JavaScript separate. This is a very good idea. However, if you want to fetch all records from MySQL using PHP and mysqli library you do not need to have any loop. You can just fetch everything into an array and then display with json_encode() in JavaScript.

<?php

// import your mysqli connection before

$result1 = $conn->query("SELECT * FROM chart_data_column WHERE value = 'now'");
$dataPoints = $result1->fetch_all(MYSQLI_ASSOC);

?>
<script>
 window.onload = function () {

   var chart = new CanvasJS.Chart("chartContainer", {
  title: {
  text: ""
      },
  axisY: {
  title: ""
      },
   data: [{
type: "line",
   dataPoints: <?= json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
   }]
   });
  chart.render();
 }
</script>

<?= is short for <?php echo

Sign up to request clarification or add additional context in comments.

Comments

0

You put the entire query inside the array. You need to separate them. Also, you have "chart_data_column" where the table name should be.

$dataPoints = array();

$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
    while ($row = $result1->fetch_assoc()) {
        $dataPoints[] = $row;
    }
}

3 Comments

Here how do i assign fetched values to x and y.. like array("y" => 25, "label" => "Sunday"), ?> sunday & 25 in the given static data.?
$row[0] will give you the first returned column value, $row[1] the second etc...
here i have 2 column values, that i need to fetch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.