在查询本身之前显示查询结果

时间:2015-04-03 06:01:02

标签: php mysql

我有这个问题:

<?php

echo $grand_total; // info on top of page

$getinfo = mysql_query("SELECT * FROM sales");
while($rows = mysql_fetch_assoc($getinfo)){
    $price = $rows['price']; // I want this to be display on top of my page before this query
    $quantity = $rows['quantity']; // I want this to be display on top of my page before this query
    $total = $price * $quantity;
    $grand_total += $total;
}

?>

我想在页面顶部显示此查询的结果。在此先感谢:)

enter image description here

3 个答案:

答案 0 :(得分:6)

在卵孵化之前,它们仍然是鸡蛋而不是鸡。在正当程序完成后,你不能告诉别人这里的鸡(已经是)将从下一个鸡蛋中孵化出来。

<强> TL; DR

这是不可能的。

深思熟虑

想象一下你有办法做到这一点,那你为什么要让母鸡坐在那些蛋上等待它们孵化?如果你已经拥有这些数据,为什么还要执行查询并浪费时间?

  

安排应该是这样的。这就像你从下到上写作。我正在处理生成计算的销售报告。但报告应该从下到上书写。 - Archie Zineg

编写一种新的网络编程语言。

现在找到解决方案

您正在查看问题并以错误的方式制定解决方案。虽然您可能希望首先填充报告的下半部分,然后从那里到顶部,但这并不意味着您无法事先获取数据。您可以轻松使用模板并按照您希望的方式填充它。您可以轻松地从顶部的数据库生成/获取此数据,而不是将其显示在任何位置,直到您到达想要使用它的位置。

答案 1 :(得分:3)

使用Javascript可能会有效。

<div id="grandtotal">0.00</div>
<?php
$getinfo = mysql_query("SELECT * FROM sales");
while($rows = mysql_fetch_assoc($getinfo)){
    $price = $rows['price']; // I want this to be display on top of my page before this query
    $quantity = $rows['quantity']; // I want this to be display on top of my page before this query
    $total = $price * $quantity;
    $grand_total += $total;
}

?>
<script>
// I am using jQuery here. Traditional js will work
$('#grandtotal').html('<?php echo $grand_total; ?>');
</script>

答案 2 :(得分:0)

正如评论和其他答案中所解释的那样,在实际检索之前,您无法回应某些内容。但是,如果您愿意,可以这样做:

<?php
getFName(); //put this line at the top of your page

function getFName(){    
    $getinfo = mysql_query("SELECT * FROM table");
    while($rows = mysql_fetch_assoc($getinfo)){
        $fname = $rows['fname']; // I want this to be display on top of my page before this query
        $lname = $rows['lname']; // I want this to be display on top of my page before this query
    }
    echo $fname; 
}
?>
相关问题