使用按钮PHP MYSQL MORRIS.JS获取特定数据

时间:2018-02-20 02:22:28

标签: php mysql morris.js

程序流程: 1.加载页面后,我有一个SQL查询,计算所有分支的平均销售额和总销售额,并使用while循环生成每个分支的按钮。 2.当我单击特定分支的销售按钮时,SQL查询应计算该分支的总销售额和平均销售额,并使用MORRIS.JS显示它。

我遇到了获取特定分支以显示总销售额和平均销售额的问题。

每个分支的按钮生成的PHP代码:

echo "var content = '<div class=".'content'.">'+
    '$image'+
    '<p class=".'street'.">".$row['street']."</p>'+
    '<span class=".'label'.">Branch:</span>'+
    '<span class=".'details'.">".$row['branch']."</span>'+
    '<span class=".'label'.">Country:</span>'+
    '<span class=".'details'.">".$row['country']."</span>'+
    '<span class=".'label'.">Barangay:</span>'+
    '<span class=".'details'.">".$row['barangay']."</span>'+
    '<span class=".'label'.">Town:</span>'+
    '<span class=".'details'.">".$row['town']."</span>'+
    '<span class=".'label'.">Province:</span>'+
    '<span class=".'details'.">".$row['province']."</span>'+
    '<span class=".'label'.">Phone:</span>'+
    '<span class=".'details'.">".$row['phone']."</span>'+
    '<span class=".'label'.">Email:</span>'+
    '<span class=".'details'.">".$row['email']."</span>'+
    '<span class=".'label'.">Website:</span>'+
    '<span class=".'details'.">".$row['website']."</span>'+
    '<a href='".$row['id']."' class=".'btn-sales'.">View Sales</button>'+
'</div>';

使用图表通过Morris.js计算所有分支和显示数据的总销售额的代码:

<div id="t-yearly-sales" style="height: 80%;"></div>
<?php
    include "connect.php";
    $sql = "SELECT year, SUM(sales) AS sales FROM tblSales GROUP BY year";
    $result = mysqli_query($conn, $sql);

    $chart = '';
    while ($row = mysqli_fetch_array($result)){
        $chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
    }                       
?>
<script>
    new Morris.Bar({
      element: 't-yearly-sales',
      data: [<?php echo $chart; ?>],
      xkey: 'year',
      ykeys: ['sales'],
      labels: ['Total Sales'],
      hideHover: 'auto'
    });
</script>

1 个答案:

答案 0 :(得分:0)

我认为你可以使用ajax调用来实现id。首先改变这个

 '<a href='".$row['id']."' class=".'btn-sales'.">View Sales</button>'

到此

 "<button onclick='chart(".$row['id'].")' class='btn-sales'>View Sales</button>"

然后你创建一个具有ajax调用的函数

function chart(id)
{
   $.ajax({
      method:GET,
      data:{keyid:id},
      url:'yourphpfunction.php',
      success:function(returnData)
      {
         new Morris.Bar({
         element: 't-yearly-sales',
         data: returnData,
         xkey: 'year',
         ykeys: ['sales'],
         labels: ['Total Sales'],
         hideHover: 'auto'
         });
      }
   });
}

在你的php文件

$sql = "SELECT year, SUM(sales) AS sales FROM tblSales where id = " . $_GET['keyid'] . " GROUP BY year";