Chartjs-Loop through multiple rows as labels and data in chart.js and PHP

2👍

Trying to dynamically build an array of JS with PHP code is never a good idea. Instead, build the array in PHP and the use json_encode to pass it to JS (or even better, use a templating engine and pass it in with data attributes, but’s that a whole other topic)

Also, you are trying to loop the result multiple times, which I’m not sure is possible. It’s been a long time since I used the native mysqli functions.

First, fetch the data and build the arrays you need to pass to Chart.js in PHP:

$statement = $con->prepare("SELECT Date_buy, Name_buy, Price_buy FROM daily_buy_orders WHERE Name_buy = ?");
$statement->bind_param('s', $ticker); // 's' specifies the variable type => 'string'
$statement->execute();
$result = $statement->get_result();

$dates = [];
$prices = [];
while ($row = $result->fetch_assoc()) {
    $dates[] = $row['Date_buy'];
    $prices[] = $row['Price_buy']
}

Now you can pass this to the chart in a much cleaner way:

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?php json_encode($dates); ?>,
        datasets: [{
            label: '# of Votes',
            data: <?php json_encode($prices); ?>,
        }]
    }
}

I haven’t tested this, but it gives you the idea

EDIT: This returns the following output:
"LOWArrayLOWArrayLOWArrayLOWArray". Where Name_buy is LOW, meaning the second print statement is bugged. How to solve this?

    $arrDates = array();
    $arrPrices = array();
    $arrNames = array();
    // $dates = [];
    // $prices = [];
    // $names = [];
    $result = $select_query->get_result();
    while ($row = mysqli_fetch_assoc($result)) {
        $arrDates[] = $row['Date_buy'];
        $arrPrices[] = $row['Price_buy'];
        $arrNames[] = $row['Name_buy'];
        print($row['Name_buy']);
        print($arrNames);
        }

Leave a comment