我想要的是在从MySQL检索的表行中添加值。
这是我的PHP文件:
<?php
mysql_connect('localhost','root','');
mysql_select_db('accounts');
$sql= "SELECT * FROM users1";
$list=mysql_query($sql);
?>
<html>
<head>
<title>Welcome to ScanNShop</title>
</head>
<h1>Welcome to ScanNShop</h1>
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>No.</th>
<th>Name</th>
<th>Price</th>
<tr>
<?php
while ($users1=mysql_fetch_assoc($list)) {
echo "<tr>";
echo "<td>".$users1['pid']."</td>";
echo "<td>".$users1['name']."</td>";
echo "<td>".$users1['price']."</td>";
}
?>
</table>
</body>
</html >
这是PHP文件的输出。
No. Name Price
1 bread 2.00
2 milk 2.00
3 janabab 6797994.00
4 jajajsh 846494.00
我想把所有的价格加起来,并显示一个echo "Total:" thetotal
我让您的代码变得简单,并添加了更改我可以给你一个其他代码,但如果你学习php,这很容易理解
我添加了更改的的评论
mysql_connect('localhost','root','');
mysql_select_db('accounts');
$sql= ('SELECT * FROM users1');
$list=mysql_query($sql);
?>
<html>
<head>
<title>Welcome to ScanNShop</title>
</head>
<h1>Welcome to ScanNShop</h1>
<body>
<table width="600" border="1" cellpadding="1" cellspacing="1">
<tr>
<th>No.</th>
<th>Name</th>
<th>Price</th>
</tr>
<?php
//set total to zero
$total=0;
while ($users1=mysql_fetch_assoc($list)) {
echo "<tr>";
echo "<td>".$users1['pid']."</td>";
echo "<td>".$users1['name']."</td>";
echo "<td>".$users1['price']."</td>";
//set total to the price + the previous total
$total = $users1['price']+$total;
echo "</tr>";
}
//display total
echo '<tr><td></td>';
echo '<td>Total:</td>';
echo '<td>'.$total.'</td></tr>';
?>
</table>
</body>
</html >
另一种求和数据行的方法是在SQL查询本身中使用GROUP by。。与ROLLUP(文档)。
示例:
SELECT Number, Min(Name) AS Name, SUM(amount) AS Price
FROM grocery_list
GROUP BY Number WITH ROLLUP
将产生输出:
Number Name Price
1 bread 2.00
2 milk 2.00
3 janabab 6797994.00
4 jajajsh 846494.00
NULL bread 7644492.00
带NULL的行是组"Number"的ALL记录中的MIN(名称)、SUM(价格)。然后,您可以根据哪个字段为NULL来筛选输出,以确定如何显示。
您可能只需要在特殊变量中对结果求和?
$sum = 0;
while ($users1=mysql_fetch_assoc($list)) {
$sum += $users1['price'];
echo '<tr>';
echo '<td>'.$users1['pid'].'</td>';
echo '<td>'.$users1['name'].'</td>';
echo '<td>'.$users1['price'].'</td>';
echo '</tr>';
}
echo '<tr>';
echo '<td></td>';
echo '<td>Total</td>';
echo '<td>'.$sum.'</td>';
echo '<tr>';
字符串不要使用双引号(")。请使用单引号(');并且不要使用mysql_*函数,它们已被弃用。