我想做的很简单。我有一个用于冰淇淋销售的MySQL数据库表,名为“ ice_cream_sales”。我在表格中看到的列是冰淇淋的“ Flavor”和“ DateTime”时间戳。我想显示每年每种口味的冰淇淋销售数量。因此,我有一个while循环,该循环执行一个SQL查询,该查询检索每年的行数,然后根据所获取行的冰淇淋口味,将其添加到适合该冰淇淋口味的PHP变量中进行计数该冰淇淋在本年度的销售额。然后,我想使用Google折线图,该折线图使用JS数组显示每年的冰淇淋销量。请访问以下链接以查看其工作原理:https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart。
但是,现在我只想看看我可以成功地将PHP变量传输到JS变量,然后将这些变量添加到JS数组中。因此,由于PHP代码嵌入在JS脚本标记中,因此我使用echo语句将PHP变量转换为JS变量。然后,我将使用每年每个风味冰淇淋的这些计数器值创建一个数组,该值将附加到用于Google折线图的数组中。当我尝试执行代码时,出现空白页面,没有错误消息。任何建议和修复将不胜感激。
当我在while语句下注释掉if语句代码块以检查冰淇淋的味道时,该代码运行良好,并且得到了[2010, 0, 0, 0], [2011, 0, 0, 0]
的输出数组,依此类推。
<script>
var toAdd = new Array();
<?php
$year = intval(2010);
while ($year <= 2019) {
include 'includes/dbh_cred.php';
$sql = "SELECT * FROM ice_cream_sales WHERE myDate LIKE '$year%'";
$chocolate = intval(0);
$vanilla = intval(0);
$strawberry = intval(0);
$result = mysqli_query($connect, $sql);
if (mysqli_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row['Flavor'] == 'Chocolate')
$chocolate = $chocolate + 1;
else if ($row['Flavor'] == 'Vanilla')
$vanilla = $vanilla + 1;
else if ($row['Flavor'] == 'Strawberry')
$strawberry = $strawberry + 1;
}
}
//chocolate, vanilla, strawberry sales for that particular year
echo "var chocolate = " . $chocolate . ";";
echo "var vanilla = " . $vanilla . ";";
echo "var strawberry = " . $strawberry . ";";
echo "var year = " . $year . ";";
//add these values to an array
echo "toAdd.push([year, chocolate, vanilla, strawberry]);";
$year = $year +1;
}
?>
var data = new Array(["Year", "Chocolate", "Vanilla", "Strawberry"]);
console.log(data[0][0] + "\t" + data[0][1] + "\t" + data[0][2] + "\t"
+ data[0][3]);
data.push(toAdd);
for(var i = 1; i < data.length; i++) {
for(var j = 0; j < data[i].length; j++) {
console.log(data[i][j]);
答案 0 :(得分:1)
这可能要简单得多。
<?php
include 'includes/dbh_cred.php';
$sql = "SELECT
YEAR(myDate) AS year,
SUM(IF(Flavor = 'chocolate', 1, 0)) AS chocolate,
SUM(IF(Flavor = 'strawberry', 1, 0)) AS strawberry,
SUM(IF(Flavor = 'vanilla', 1, 0)) AS vanilla
FROM ice_cream_sales
GROUP BY YEAR(myDate)";
$result = $connect->query($sql);
if ($result->num_rows) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
?>
<script>
var data = <?php echo json_encode($data);?>;
</script>
这是SQL的演示:http://sqlfiddle.com/#!9/f7ca1b/3/0。基本上,它会为每种口味维护一个计数器,然后按年份将其分组,因此所有数据都将作为数据库查询的一部分进行编译。然后,在PHP中需要做的就是将记录放入数组中并以JSON格式输出。
我建议使用PDO进行数据库访问,因为它更容易学习,并且可使代码更加简洁。
答案 1 :(得分:0)
Try follow SQL, may it easy for you?
select Flavor,count(*) from ice_cream_sales WHERE myDate LIKE '$year%' group by Flavor