我在做什么: 使用PHP从MySQL获取推文数据;将PHP输出分配给Javascript数组;将JS数组作为参数传递给C3.js。
问题: MySQL DB不断更新。所以我也需要更新C3图。我的问题是我正在混合使用PHP和JS,因此我无法将它们捆绑到同一个函数中并调用此函数。 如何从数据库中获取新数据并更新图表? 这是代码:
<?php
// Fetch data from DB
$sql = "SELECT created_at, COUNT(text) as tweetcounts from brexittweets group by created_at order by created_at desc limit 100";
$result = $conn->query($sql);
?>
<script>
var timeStamps = [];
var statusesCount = [];
timeStamps.push('timeStamps');
statusesCount.push('statuses');
<?php
if ($result->num_rows > 0) {
// assign PHP output to JS variables
while($row = $result->fetch_assoc()) { ?>
timeStamps.push('<?php echo $row['created_at'];?>');
statusesCount.push('<?php echo $row['tweetcounts'] ?>');
console.log(timeStamps);
<?php
}
} else {
echo "0 results";
}
?>
</script>
<?php echo '<div id ="chart2"></div>'?>
<script>
var chart = c3.generate({
bindto: '#chart2',
data: {
x: 'timeStamps',
xFormat: '%Y-%m-%d %H:%M:%S',
columns: [
timeStamps,
statusesCount
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format:'%H:%M:%S'
}
}
}
});
setTimeout(function () {
// Need to fetch fresh data here
}