Chartjs-How to loop inside javascript using php variable

0👍

The reason is because you’re repeating the same variable within your data and labels:

data : [<?php echo $arrdata1; ?>,<?php echo $arrdata1; ?>, ...
labels : ["<?php echo $arrLabels1; ?>","<?php echo $arrLabels1; ?>", ...

Try getting all the data from the database into a PHP array first, then output that array into JSON, (where JavaScript will be able to understand it properly).

For example:

$arrdata = array();
$arrLabels = array();

while ($chartrows = mysql_fetch_object($chartr)) {

    $monthdate = strtotime($chartrows->date);
    $todate = date("M", $monthdate);

    $arrLabels[] = $todate;
    $arrdata[] = $chartrows->item_price;

}

Now move your output outside of the while loop, you’re only generating one chart.

So in your JavaScript (as noted in the previous sentence, this should be outside of the while loop).

var lineChartData = {

    label : <?php json_encode($arrLabels); ?>,

    datasets: [

        {
            label: "My Second dataset",
            fillColor: "rgba(48, 164, 255, 0.2)",
            strokeColor: "rgba(48, 164, 255, 1)",
            pointColor: "rgba(48, 164, 255, 1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(48, 164, 255, 1)",

            data : <?php json_encode($arrdata); ?>
        }

    ]

};

Also I noticed that you’re not sanitizing your query:

$id    = $_REQUEST['ID'];
$item1 = $_REQUEST['item'];

$sql = "SELECT * FROM item WHERE item_sup_company = '$id' AND subcategory = '$item1' ORDER BY item_id DESC";

You should be preparing/executing or at the very least escaping the data within the query. Please take a look at this.

Leave a comment