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
i want to add all the tuition of id-8 and echo the result of the sum of the tuition. how can i sum all the tuition with out adding the tuition of other id’s. the table name is “students_payments”… “i also want to echo the tuition of an id in its own page, like when i access the account of id-8 it shows the sum of its tuition. 😀
i have this code, but when i access the account of id-9 and id-10 it shows the added value of all the tuition. tnx in advanced.. 😀
<?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";
}
}
?>
A few things about your code:
Always cast data to what you expect them to be (in the case of your id, that should be an integer).
Never put any unescaped strings into SQL queries. You never know what people type into your applications input fields. In this case I don’t use mysql_escape, as the id was casted to integer, which is of no harm to the query.
Never (!) use mysql_query in a loop. You never need it and it will always slow down your application without providing any use.
If your database expects an integer, then give it an integer and not a string. id is expected to be an integer, but ‘$id’ will always be a string. Unfortunately MySQL silently tries to cast this to integer instead of complaining…
As I am very picky: id is an abbreviation for identifier, which in turn means, that you can identify something by it. Resulting from that, an identifier must always be unique. I hope you chose it merely to explain your question.
Use ‘ instead of ” for strings wherever you can. This will keep the PHP parser from trying to interpret the string. Makes your code a little more save and faster.
Though mysql_* functions are deprecated, I have only extended your code. So for an answer to your question see the code below.
You can add some more debugging code such as mysql_error() to find errors in your SQL statements. But don’t display that to your users. They might know, how use it for exploiting your application…