PHP SQL查询转换为chart.js柱状图 – 与数组有关的问题

huangapple go评论99阅读模式
英文:

PHP SQL Query into a chart.js bar chart - Issue with the array

问题

以下是翻译好的部分:

"I'm successfully getting the sql data into an array, what I can't seem to work out is how to get that array to show in a chart.js chart. I can get the array into the dataset section but for some reason it isn't rendered? The chart.js code is as-is off the website so excuse the default bits and pieces, I aim to tweak those once I have the data displaying OK."

我的代码成功将SQL数据存入数组中,但我似乎无法弄清楚如何在chart.js图表中显示该数组。我可以将数组放入数据集部分,但出现某种原因,它没有渲染? chart.js代码如网站上所示,所以请原谅其中的默认部分,我打算在数据显示正常后进行调整。

"A page view of the results shows the array inside the dataset section:"

结果的页面视图显示数据数组位于数据集部分内。

"Can anyone throw any pointers to where this is going wrong? Thanx"

有人可以指出这出了什么问题吗?谢谢

"My final solution to this following the advice was:"

根据建议,我对此的最终解决方案是:

英文:

I'm successfully getting the sql data into an array, what I can't seem to work out is how to get that array to show in a chart.js chart. I can get the array into the dataset section but for some reason it isn't rendered? The chart.js code is as-is off the website so excuse the default bits and pieces, I aim to tweak those once I have the data displaying OK.

My code is as follows;

  1. <?php
  2. //print_r($_POST);
  3. $month = $_POST["month"];
  4. $year = $_POST["year"];
  5. $type = $_POST["type"];
  6. //can build sql strings in this ifelse block
  7. if ($type == "both") {
  8. $sql = "SELECT * FROM solar_generation WHERE MONTH(timestamp)= $month AND YEAR(timestamp) = $year";
  9. } elseif ($type == "generation") {
  10. $sql = "SELECT timestamp, generation FROM solar_generation WHERE MONTH(timestamp)= $month AND YEAR(timestamp) = $year";
  11. } else{
  12. $sql = "SELECT timestamp, export FROM solar_generation WHERE MONTH(timestamp)= $month AND YEAR(timestamp) = $year";
  13. }
  14. echo $sql;
  15. $host = "*******";
  16. $dbname = "solar_generation";
  17. $username = "*******";
  18. $password = "*******";
  19. $connection = mysqli_connect(hostname: $host,
  20. username: $username,
  21. password: $password,
  22. database: $dbname);
  23. if (mysqli_connect_errno()) {
  24. die("Connection error: " . mysqli_connect_error());
  25. }
  26. //Do stuff here
  27. try{
  28. $result = mysqli_query($connection, "$sql");
  29. echo "Returned rows are: " . $result -> num_rows;
  30. print("Result of the SELECT query: ");
  31. print_r($result);
  32. }
  33. catch (Exception $e) {
  34. echo 'Caught exception: ', $e->getMessage(), "\n";
  35. }
  36. $dataPoints = array();
  37. if ($result->num_rows > 0) {
  38. while ($row = $result->fetch_assoc()) {
  39. $dataPoints[] = $row;
  40. }
  41. }
  42. mysqli_close($connection);
  43. ?>
  44. <div>
  45. <canvas id="myChart"></canvas>
  46. </div>
  47. <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  48. <script>
  49. const ctx = document.getElementById('myChart');
  50. new Chart(ctx, {
  51. type: 'bar',
  52. data: {
  53. labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
  54. datasets: [{
  55. label: 'Testing',
  56. data: [<?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>],
  57. borderWidth: 1
  58. }]
  59. },
  60. options: {
  61. scales: {
  62. y: {
  63. beginAtZero: true
  64. }
  65. }
  66. }
  67. });
  68. </script>

A page view of the results shows the array inside the dataset section:

  1. data: [[{"timestamp":"2023-07-04 23:59:02","generation":0},{"timestamp":"2023-07-05 23:59:02","generation":26},{"timestamp":"2023-07-06 23:59:02","generation":28},{"timestamp":"2023-07-07 23:59:02","generation":43},{"timestamp":"2023-07-08 23:59:02","generation":20},{"timestamp":"2023-07-09 23:59:02","generation":32},{"timestamp":"2023-07-11 23:59:02","generation":22},{"timestamp":"2023-07-12 23:59:02","generation":35},{"timestamp":"2023-07-14 23:59:02","generation":8},{"timestamp":"2023-07-15 23:59:02","generation":33},{"timestamp":"2023-07-16 23:59:02","generation":28},{"timestamp":"2023-07-17 16:23:31","generation":35.4},{"timestamp":"2023-07-18 23:00:00","generation":16.2},{"timestamp":"2023-07-19 23:00:00","generation":28},{"timestamp":"2023-07-20 23:00:00","generation":23.9},{"timestamp":"2023-07-21 23:00:00","generation":21.7},{"timestamp":"2023-07-22 23:00:02","generation":14.4}]],

Can anyone throw any pointers to where this is going wrong?
Thanx

My final solution to this following the advice was:

  1. <div>
  2. <canvas id="myChart" style="height:300px"></canvas>
  3. </div>
  4. <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  5. <script>
  6. const ctx = document.getElementById('myChart');
  7. new Chart(ctx, {
  8. type: 'bar',
  9. data: {
  10. datasets: [{
  11. label: 'Solar - Generated kWh',
  12. data: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>,
  13. borderColor: '#000',
  14. backgroundColor: '#FFCC00',
  15. borderWidth: 1,
  16. parsing: {
  17. yAxisKey: 'generation'
  18. }
  19. },{
  20. label: 'Solar Exported kWh',
  21. data: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>,
  22. borderColor: '#000',
  23. backgroundColor: '#ED7014',
  24. borderWidth: 1,
  25. parsing: {
  26. yAxisKey: 'export'
  27. }
  28. }
  29. ]
  30. },
  31. options: {
  32. parsing: {
  33. xAxisKey: 'timestamp',
  34. },
  35. scales: {
  36. y: {
  37. beginAtZero: true
  38. }
  39. }
  40. }
  41. });

答案1

得分: 0

为了解决这个问题,您应该修改PHP代码,直接分配$dataPoints数组,而不添加额外的嵌套级别。以下是更新后的PHP代码:

  1. $dataPoints = array();
  2. if ($result->num_rows > 0) {
  3. while ($row = $result->fetch_assoc()) {
  4. $dataPoints[] = $row['generation']; // 假设'generation'是您想在图表中显示的数据点
  5. }
  6. }
英文:

To resolve this, you should modify the PHP code to directly assign the $dataPoints array without adding an extra level of nesting. Here's the updated PHP code:

  1. $dataPoints = array();
  2. if ($result->num_rows > 0) {
  3. while ($row = $result->fetch_assoc()) {
  4. $dataPoints[] = $row['generation']; // Assuming 'generation' is the data point you want to show in the chart
  5. }
  6. }
  7. </details>
  8. # 答案2
  9. **得分**: 0
  10. 要*开始*查看您的数据,您需要执行以下操作:
  11. - 删除围绕数据生成的 PHP 的方括号,或者使用其他方法删除输出中的一个方括号层级(js 数组文字) - `data` 应该是一个对象数组,而不是一个对象数组的数组。
  12. ```lang-php
  13. data: &lt;?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?&gt;,
  14. ```
  15. - 删除 `labels` 数组
  16. - 添加 `options.parsing.xAxisKey: 'timestamp'``options.parsing.yAxisKey: 'generation'`,以指示哪个属性应该放在 x 轴上,哪个属性应该放在 y 轴上 [文档链接](https://www.chartjs.org/docs/latest/general/data-structures.html#object-using-custom-properties)。
  17. 有了这些,您将会得到类似以下的效果:
  18. ```lang-js
  19. const ctx = document.getElementById('myChart');
  20. new Chart(ctx, {
  21. type: 'bar',
  22. data: {
  23. //labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
  24. datasets: [{
  25. label: 'Testing',
  26. data: [{"timestamp":"2023-07-04 23:59:02","generation":0},{"timestamp":"2023-07-05 23:59:02","generation":26},{"timestamp":"2023-07-06 23:59:02","generation":28},{"timestamp":"2023-07-07 23:59:02","generation":43},{"timestamp":"2023-07-08 23:59:02","generation":20},{"timestamp":"2023-07-09 23:59:02","generation":32},{"timestamp":"2023-07-11 23:59:02","generation":22},{"timestamp":"2023-07-12 23:59:02","generation":35},{"timestamp":"2023-07-14 23:59:02","generation":8},{"timestamp":"2023-07-15 23:59:02","generation":33},{"timestamp":"2023-07-16 23:59:02","generation":28},{"timestamp":"2023-07-17 16:23:31","generation":35.4},{"timestamp":"2023-07-18 23:00:00","generation":16.2},{"timestamp":"2023-07-19 23:00:00","generation":28},{"timestamp":"2023-07-20 23:00:00","generation":23.9},{"timestamp":"2023-07-21 23:00:00","generation":21.7},{"timestamp":"2023-07-22 23:00:02","generation":14.4}],
  27. borderWidth: 1
  28. }]
  29. },
  30. options: {
  31. parsing: {
  32. xAxisKey: 'timestamp',
  33. yAxisKey: 'generation'
  34. },
  35. scales: {
  36. y: {
  37. beginAtZero: true
  38. }
  39. }
  40. }
  41. });
  42. ```
  43. ```lang-html
  44. <canvas id="myChart" style="height:500px"></canvas>
  45. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.0/chart.umd.js" integrity="sha512-CMF3tQtjOoOJoOKlsS7/2loJlkyctwzSoDK/S40iAB+MqWSaf50uObGQSk5Ny/gfRhRCjNLvoxuCvdnERU4WGg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  46. ```
  47. <details>
  48. <summary>英文:</summary>
  49. To *start* seeing your data, you have to do the following:
  50. - drop the square parentheses around data generating php, or use some other method to drop one level of square parentheses (js array literal) in the output - `data` should be an array of objects, not an array of arrays of objects.
  51. ```lang-php
  52. data: &lt;?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?&gt;,
  53. ```
  54. - delete the `labels` array
  55. - add `options.parsing.xAxisKey: &#39;timestamp&#39;`, `options.parsing.yAxisKey: &#39;generation&#39;`
  56. to indicate which property should go to the x axis and which one to the y axis [doc link](https://www.chartjs.org/docs/latest/general/data-structures.html#object-using-custom-properties).
  57. With these, you&#39;ll get something like:
  58. &lt;!-- begin snippet: js hide: false console: false babel: false --&gt;
  59. &lt;!-- language: lang-js --&gt;
  60. const ctx = document.getElementById(&#39;myChart&#39;);
  61. new Chart(ctx, {
  62. type: &#39;bar&#39;,
  63. data: {
  64. //labels: [&#39;Red&#39;, &#39;Blue&#39;, &#39;Yellow&#39;, &#39;Green&#39;, &#39;Purple&#39;, &#39;Orange&#39;],
  65. datasets: [{
  66. label: &#39;Testing&#39;,
  67. data: [{&quot;timestamp&quot;:&quot;2023-07-04 23:59:02&quot;,&quot;generation&quot;:0},{&quot;timestamp&quot;:&quot;2023-07-05 23:59:02&quot;,&quot;generation&quot;:26},{&quot;timestamp&quot;:&quot;2023-07-06 23:59:02&quot;,&quot;generation&quot;:28},{&quot;timestamp&quot;:&quot;2023-07-07 23:59:02&quot;,&quot;generation&quot;:43},{&quot;timestamp&quot;:&quot;2023-07-08 23:59:02&quot;,&quot;generation&quot;:20},{&quot;timestamp&quot;:&quot;2023-07-09 23:59:02&quot;,&quot;generation&quot;:32},{&quot;timestamp&quot;:&quot;2023-07-11 23:59:02&quot;,&quot;generation&quot;:22},{&quot;timestamp&quot;:&quot;2023-07-12 23:59:02&quot;,&quot;generation&quot;:35},{&quot;timestamp&quot;:&quot;2023-07-14 23:59:02&quot;,&quot;generation&quot;:8},{&quot;timestamp&quot;:&quot;2023-07-15 23:59:02&quot;,&quot;generation&quot;:33},{&quot;timestamp&quot;:&quot;2023-07-16 23:59:02&quot;,&quot;generation&quot;:28},{&quot;timestamp&quot;:&quot;2023-07-17 16:23:31&quot;,&quot;generation&quot;:35.4},{&quot;timestamp&quot;:&quot;2023-07-18 23:00:00&quot;,&quot;generation&quot;:16.2},{&quot;timestamp&quot;:&quot;2023-07-19 23:00:00&quot;,&quot;generation&quot;:28},{&quot;timestamp&quot;:&quot;2023-07-20 23:00:00&quot;,&quot;generation&quot;:23.9},{&quot;timestamp&quot;:&quot;2023-07-21 23:00:00&quot;,&quot;generation&quot;:21.7},{&quot;timestamp&quot;:&quot;2023-07-22 23:00:02&quot;,&quot;generation&quot;:14.4}],
  68. borderWidth: 1
  69. }]
  70. },
  71. options: {
  72. parsing: {
  73. xAxisKey: &#39;timestamp&#39;,
  74. yAxisKey: &#39;generation&#39;
  75. },
  76. scales: {
  77. y: {
  78. beginAtZero: true
  79. }
  80. }
  81. }
  82. });
  83. &lt;!-- language: lang-html --&gt;
  84. &lt;canvas id=&quot;myChart&quot; style=&quot;height:500px&quot;&gt;&lt;/canvas&gt;
  85. &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.0/chart.umd.js&quot; integrity=&quot;sha512-CMF3tQtjOoOJoOKlsS7/2loJlkyctwzSoDK/S40iAB+MqWSaf50uObGQSk5Ny/gfRhRCjNLvoxuCvdnERU4WGg==&quot; crossorigin=&quot;anonymous&quot; referrerpolicy=&quot;no-referrer&quot;&gt;&lt;/script&gt;
  86. &lt;!-- end snippet --&gt;
  87. </details>

huangapple
  • 本文由 发表于 2023年7月24日 01:05:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76749436.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定