id 1stPayment 2ndPayment 3rdPayment 4thPayment Tuition
8 0 200 2000 2000 9000
8 2000 0 0 0 0
9 0 0 0 0 1000
10 1 0 0 0 0我想将id-8的所有学费相加,并回显学费总和的结果。不加上其他id的学费,怎么把所有的学费都加起来,表名是“students_payments”……“我还想在自己的页面中回显一个id的学费,比如当我访问id-8的账户时,它会显示其学费的总和。:D
我有这个代码,但当我访问id-9和id-10的帐户时,它显示了所有学费的附加值。tnx处于高级状态..:D
<?php
include("confstudents.php");
$id = $_GET['id'];
$result = mysql_query("select * from student_payments where id='$id' ");
while ($res = mysql_fetch_assoc($result)) {
$result = mysql_query("SELECT SUM(Tuition) FROM student_payments");
while ($row = mysql_fetch_assoc($result)) {
$TT = $row['SUM(Tuition)'];
echo "Php $TT";
}
}
?> 发布于 2013-01-30 21:38:11
关于你的代码的一些事情:
总是将数据转换为您期望的值(对于您的id,它应该是一个整数)。
切勿将任何未转义的字符串放入SQL查询中。你永远不会知道人们在你的应用程序输入字段中输入了什么。在本例中,我没有使用mysql_escape,因为id被强制转换为整数,这对查询没有坏处。
从不(!)在循环中使用mysql_query。你永远不需要它,它总是会减慢你的应用程序的速度,而不提供任何用途。
如果你的数据库需要一个整数,那么给它一个整数,而不是一个字符串。id应为整数,但'$id‘将始终为字符串。不幸的是,MySQL默默地尝试将其转换为整数,而不是抱怨...
因为我很挑剔: id是identifier的缩写,这反过来意味着你可以通过它来识别一些东西。因此,标识符必须始终是唯一的。我希望你选择它仅仅是为了解释你的问题。
尽可能使用‘而不是“作为字符串。这将防止PHP解析器尝试解释字符串。使您的代码更节省和更快。
尽管mysql_*函数已被弃用,但我只是扩展了您的代码。因此,对于您的问题的答案,请参阅以下代码。
<?php
include("confstudents.php");
$id = (int)$_GET['id']; // cast to int to prevent SQL injection; if you can't do that (e.g. it is a string), use mysql_escape()
if ($id <= 0) { // check if the id is at all valid and break here if it isn't
die('Invalid ID');
}
$result = mysql_query('SELECT SUM(tuition) sum_tuition FROM student_payments WHERE id = ' . $id);
if ($result === FALSE) { // Check if the statement was able be processed
die('Error in SQL statement'); // break here, if it wasn't
}
$res = mysql_fetch_assoc($result); // with the SQL above, there's always exactly one row in the result
echo 'Php ' . $res['sum_tuition'];
?>您可以添加更多的调试代码,比如mysql_error()来查找SQL语句中的错误。但不要将其显示给用户。他们可能知道,如何使用它来利用您的应用程序……
发布于 2013-01-30 20:44:57
您的查询应该是
SELECT SUM(Tuition) as TotalTuition FROM student_payments WHERE id='$id' GROUP BY id然后你就可以回显TotalTuition了。
警告
您的代码容易受到sql injection的攻击,您需要避开所有get和post,更好的方法是使用Prepared statement
好读
便笺
PHP整个ext/mysql扩展提供了所有以mysql_前缀命名的函数,它是officially deprecated as of PHP v5.5.0,将来将被删除。因此请使用PDO或MySQLi
好读
发布于 2013-01-30 20:54:38
<?php
include("confstudents.php");
$id = $_GET['id'];
$result = mysql_query("SELECT SUM(Tuition) FROM student_payments where id='$id'");
while ($row = mysql_fetch_array($result)) {
$TT = $row['SUM(Tuition)'];
echo "$TT";
}
?>https://stackoverflow.com/questions/14604204
复制相似问题