0

当有人选择一个服务号时,它会弹出并只给出一条记录。我希望它从两张桌子中得到总计..

<?php

   $qry = mysql_query ("SELECT SUM(fruit) AS total FROM fruitinventory WHERE `fruitcolor` LIKE '%{$_POST['select']}%'");

$row2 = mysql_fetch_assoc($qry);


    echo $row['total'];

?>

<?php

   $qry = mysql_query ("SELECT SUM(fruitsmart) AS total FROM fruitrotten WHERE `fruitcolor` LIKE '%{$_POST['select']}%'");

$row = mysql_fetch_assoc($qry);


    echo $row['total'];

?>

然后

我也希望同时显示两行的总数。

<?php 

$total return = $row+$row2 

?>
4

3 回答 3

0

假设你想为你的代码保留同样的结构,你可以像这样显示一个总数(注意:MySQLi(i = 改进)函数应该被使用,因为 MySQL 函数已被弃用):

<?php

$qry = mysqli_query ("SELECT SUM(fruit) AS total FROM fruitinventory WHERE `fruitcolor` LIKE '%{$_POST['select']}%'");
$row2 = mysqli_fetch_assoc($qry);
echo $row2['total'];


$qry = mysqli_query ("SELECT SUM(fruitsmart) AS total FROM fruitrotten WHERE `fruitcolor` LIKE '%{$_POST['select']}%'");
$row = mysqli_fetch_assoc($qry);
echo $row['total'];

$total = $row['total'] + $row2['total'];
echo $total;

?>

既然它会出现,我建议您考虑使用PDO而不是 mysql_ (或至少将mysqli_real_escape_string包裹在您的变量周围)来保护您的数据库。

于 2012-07-12T01:03:39.670 回答
0

您可以将两个数据库调用合并到一个查询中,并使用结果的列作为变量来回显:

<?php
    $input = mysql_real_escape_string($_POST['select']);
    $sql = "
        SELECT
            (
                SELECT SUM(fruit) 
                FROM fruitinventory 
                WHERE fruitcolor LIKE '%$input%'
            ) AS totalfruit,
            (
                SELECT SUM(fruitsmart) 
                FROM fruitrotten 
                WHERE fruitcolor LIKE '%$input%'
            ) AS totalfruitsmart";
    $qry = mysql_query($sql);
    $row = mysql_fetch_assoc($qry);

    echo $row['totalfruit'] . '<br />';
    echo $row['totalfruitsmart'] . '<br />';
    echo $row['totalfruit'] + $row['totalfruitsmart'];
?>

请至少使用它mysql_real_escape_string()来帮助防止 SQL 注入攻击,这是您的原始代码广泛开放的。

于 2012-07-12T02:27:47.290 回答
0

您可以尝试仅使用 SQL 进行求和。如下所示:

$qry = mysql_query ("

    SELECT (

        ( SELECT SUM(fruit) AS total FROM fruitinventory WHERE `fruitcolor` LIKE '%{$_POST['select']}%' ) + 

        ( SELECT SUM(fruitsmart) AS total FROM fruitrotten WHERE `fruitcolor` LIKE '%{$_POST['select']}% )

    ) AS total") ;

$row = mysql_fetch_assoc($qry);

echo $row['total'];
于 2012-07-12T01:31:14.633 回答