PDA

View Full Version : totalling number in php/mysql


sir pannels
01-12-2003, 02:42 AM
hey
ok so what im trying to get at here is working out the total of something.
say for instances there is a table called USERS and there are sevral users, each user has a field called "number"
how would i work out what every users number is totalled..
so like user 1 number +user 2 number = user 3 and so forth.. i have this...

$conn=@mysql_connect("localhost", "", "")
or die("Could not connect");

$rs = @mysql_select_db("GAME", $conn)
or die("Could not select database");

$query="SELECT number FROM users";

#execute the query
$rs=mysql_query($query,$conn)
or die("Could not execute query");

but im lost as what to put when it does the query , as in the php code to work out the total number.
could i get a little help?
thanks :thumbsup:

firepages
01-12-2003, 03:41 AM
So you want the sum of the numbers ??


<?
//connect etc//
$yaks=mysql_query("SELECT SUM(number) as sum FROM users") or die(mysql_error());

//echo mysql_result($yaks,0);

//OR//

$r=mysql_fetch_array($yaks);
echo $r['sum'];
?>


if not please explain again as I am not sure if thats what you actually want.

sir pannels
01-12-2003, 03:51 AM
Hey
yes thats what i wanted thank you:)
however, im cant work out how to add that to the query i already have .. how can i run two querys? and where do the $rs `s go in accordanation to eachother?
thanks FriarFire :thumbsup:

firepages
01-12-2003, 04:13 AM
<?
$conn=@mysql_connect("localhost", "", "")
or die("Could not connect");

$rs = @mysql_select_db("GAME", $conn)
or die("Could not select database");

$query1="SELECT number FROM users";
$query2="SELECT SUM(number) FROM users";

#execute the queries
$sum=mysql_query($query2,$conn)or die("Could not execute query");
$numbers=mysql_query($query1,$conn)or die("Could not execute query");

#fetch the data
$total=mysql_result($sum,0);
echo $total;

while($yaks=mysql_fetch_row($numbers)){
echo $row[0].'<br />';
}
?>


but I gotta say I HATE the $conn= method... you can use the
following without having to worry about carrying the $conn
around everywhere...(you only really need it if you are querying
multiple databases in the same script)


<?
@mysql_connect("localhost", "", "")or die("Could not connect");
@mysql_select_db("GAME")or die("Could not select database");

$query1="SELECT number FROM users";
$query2="SELECT SUM(number) FROM users";

#execute the queries
$sum=mysql_query($query2)or die("Could not execute query");
$numbers=mysql_query($query1)or die("Could not execute query");

#fetch the data
$total=mysql_result($sum,0);
echo $total;

while($yaks=mysql_fetch_row($numbers)){
echo $row[0].'<br />';
}
?>


edited !

sir pannels
01-12-2003, 04:48 AM
Thanks thats realy helpfull,
ill play about with it in the morning once my eyes open :D

P