Hello,

I was wondering if anyone could help me as I am trying to add all the rows of a particular field in a MySQL table using PHP.

I have a table named members2 which has a field named points! What I want to be able to do is display the total number of points currently in the site that all members have!

But I have no idea how to do this and cannot seem to find anything when googling it!

Any help is much appreciated!

Justin

Recommended Answers

All 4 Replies

you can try something like this:

$query="Select points from members2";
$result=mysql_query($query);

$total=0;
while($row=mysql_fetch_array($result))
{
$total=$total + $row['points'];
}

echo "Total is:" . $total;

Easier:

$query="SELECT SUM(points) AS `total` from members2";

$result=mysql_query($query);
while($row=mysql_fetch_assoc($result))
  $total = $row['total'];

If you want to limit the sum to certain sets of data, you will have to use the GROUP BY function in mysql. Learning about grouping and its associated functionality will help you avoid a lot of tedious, repetitive coding.

Easier:

$query="SELECT SUM(points) AS `total` from members2";

$result=mysql_query($query);
while($row=mysql_fetch_assoc($result))
  $total = $row['total'];

If you want to limit the sum to certain sets of data, you will have to use the GROUP BY function in mysql. Learning about grouping and its associated functionality will help you avoid a lot of tedious, repetitive coding.

much easier:

$query="SELECT SUM(points) AS `total` from members2";
$result=mysql_query($query);
$total=mysql_result($result,0,"total");
commented: interesting. haven't had much use for just pulling one field per query, but it piqued my interest +2

Thank you so much! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.