I have a table in my database named club
. In club
there's a row called speler_id
with this speler_id
i can get the value of the speler_id
. I want to count the values together (because a user has more than 1 speler_id
) this is the code:
$punten = 0;
$sql2 = "SELECT * FROM `club` WHERE `user_id`=" . $userid ." ";
$result2 = mysql_query($sql2) or die('Query failed: ' . mysql_error());
while( $row2 = mysql_fetch_assoc( $result2)) {
$sql = "SELECT * FROM `players_db` WHERE `id`=" . $row2['speler_id'] . " ";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
$row = mysql_fetch_assoc( $result);
$punten += $row['xb_end_range'];
echo $punten;
}
but when I execute this, it gives me all the values not the value total.
Sorry for using mySQL will update it to PDO or mySQLi soon.
EDIT
I found the answer:
$sql = "SELECT SUM(xb_end_range) AS punten
FROM club AS c
JOIN players_db AS p ON c.speler_id = p.id
WHERE c.user_id = $userid";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$punten = $row['punten'];
echo number_format("$punten")
In general, try to avoid doing queries inside a loop. Instead, join the tables.
$sql = "SELECT SUM(xb_end_range) AS punten
FROM club AS c
JOIN players_db AS p ON c.speler_id = p.id
WHERE c.user_id = $userid";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$punten = $row['punten'];
echo $punten;
In the first place, you are manually joining the club
table to the players_db
table, but it would be far more efficient, both in code and in running time, to let the DB do it for you. In the second place, you are performing a manual aggregation (or attempting to do), which also would be more efficiently performed by the database. Overall, it looks like you want to execute a query something like this:
select ifnull(sum(p.xb_end_range), 0) as punten
from
club c
join players_db p on p.id = c.speler_id
where c.user_id = 'the-user-id'
That will return exactly one row with what I take to be the desired sum as as the value of the only column, "punten".