[thelist] PHP/MySQL/sum()

rogerharness at comcast.net rogerharness at comcast.net
Sun Apr 9 03:04:17 CDT 2006


E'volters,

I'm not really a 'from scratch" PHP/MySQL programmer. I just try to cut/paste/re-use code and try to make it work for whatever I'm trying to do. I know that the way I have this database set up would probably drive most real programmers crazy.

I only have 6 fields;
name
unique_id
class
class_date
hours
auto_number

In the database, there can be multiple records for the same person, with his same unique_id, but all for different classes, (Access, Excel, etc.).

With the following code, I'm able to successfully view all the person's classes, class dates, and class hours. But what I can't do is get a total of the hours. If Microsoft Access is 8 hours, and Microsoft Excel is 6 hours, I would like the total_hours to print 14. I've been messing with the sum() function, but no matter what I do, I can't get my PHP code to print it to the screen.

If I'm actually logged into my database, I'm able to do the 'select sum(hours) from my_table' thing, and get THAT to give me a correct total, but again, I can't get anything like that to actually work on my PHP/HTML page. I've googled/searched/etc, and have found tips, but I just can't seemt to make anything actually work. 

Does anyone have any help/pointers/advise with this situation?

Thank you for any help. (and please ignore the sloppy code/etc. A work in progress,

-Roger Harness

mysql_select_db("my_database");
$query = "select * from my_table where unique_id = '$unique_id'";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);

echo "<p>Number of Completed classes: ".$num_results."</p>";

echo "<table border=1>";

for ($i=0; $i <$num_results; $i++)

{
        $row=mysql_fetch_array($result);

        echo "</td><td align=right>";
        echo htmlspecialchars( stripslashes($row["class_date"]));
        echo "</td>";

        echo "<td>";
        echo htmlspecialchars( stripslashes($row["class"]));
        echo "</td>";

        echo "<td>";
        echo ($row["hours"]);
        echo "</td></tr>";
}
echo "</table>";



More information about the thelist mailing list