不能在数据集

时间:2017-03-14 16:57:18

标签: javascript php mysql d3.js

我试图创建一个需要MySQL数据库数据的D3.js图表​​。该图表是使用JavaScript制作的,但我想用数据库值替换值。

如果我只尝试使用PHP输入一个值,这是有效的,但如果我再添加则不行。

var dataset = [
    { name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
      echo "".$row["data1"].""; } ?>},
]; // This works

然而,上述工作并非如此:

var dataset = [
    { name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) {
      echo "".$row["data1"].""; } ?>},

    { name: 'data2', percent: <?php while($row = mysqli_fetch_array($result)) {
      echo "".$row["data2"].""; } ?>}

]; // Adding another PHP value stops the entire chart from working (it works if I use a non-PHP second value).

我还尝试对所有数据使用一个while循环,但这也不起作用。

<?php $connect = mysqli_connect("host", "user", "pass", "db");  
 $query = "SELECT data1, data2 FROM database WHERE x = y;
 $result = mysqli_query($connect, $query); ?>

我确信数据不是问题所在。我在谷歌图表上尝试过同样的事情,但没有问题。

2 个答案:

答案 0 :(得分:2)

#create an array for the objects
$datasets=array();

#very unclear if your code fetches one or more rows, 
#it seems one row with dataX fields
$row = mysqli_fetch_array($result);
#So we go over it
foreach($row as $field => $value) {
     #create an object that becomes later {name:'abc',percent:'12'}
     $obj = new stdClass();
     $obj->name = $field;
     $obj->percent=$value;
     #collect it in the array, 
     #it becomes lates [{name:'abc',percent:'12'},{...},{...}]
     $datasets[] = $obj;
}
#parse the data into the javascript part of the html content
?>
var datasets = <?php print json_encode($datasets);?>;
<?php

希望你可以使用它。

答案 1 :(得分:0)

如果这是您正在使用的真实代码,那么PHP的第一位会消耗var dataset = [ { name: 'data1', percent: <?php while($row = mysqli_fetch_array($result)) { echo "".$row["data1"].""; } ?>}, // $result has already been fully consumed { name: 'data2', percent: <?php while($row = mysqli_fetch_array($result)) { echo "".$row["data2"].""; } ?>} ]; 中保存的所有结果集,因此PHP的第二位没有返回任何内容

for (Leerling l : leerlingen) {
    System.out.println(l);
}