当有人选择服务号码时,它会弹出并只提供一条记录。我想让它从两张表中给出总数..
<?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
?>
答案 0 :(得分:0)
假设你想为你的代码保留相同类型的结构,你可以像这样显示总数(注意:应该使用MySQLi(i =改进的)函数,因为MySQL函数是deprecated):
<?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)来保护您的数据库。
答案 1 :(得分: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'];
答案 2 :(得分: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注入攻击,这是您的原始代码广泛开放。