tags:

views:

156

answers:

4
    function get_total_adults()
{
    $sql = "SELECT SUM(number_adults_attending) as number_of_adults FROM is_nfo_rsvp";
    $result = mysql_query($sql) or die(mysql_error());
    $array = mysql_fetch_assoc($result);

    return $array['number_of_adults'];
}

I know there is a way to write this with less code. I'm just looking for the best way (without using something like ezSQL).

A: 

You can drop the "as number_of_adults" part of the query and use mysql_result.

phjr
A: 

You could also try refactormycode.com

Brabster
+1  A: 
function get_total_adults() {
    $sql = 'SELECT SUM(number_adults_attending) FROM is_nfo_rsvp';
    $result = mysql_query($sql) or die(mysql_error());
    // I'd throw a catchable exception (see below) rather than die with a MySQl error

    return mysql_result($result, 0);
}

As to how I'd rather handle errors:

function get_total_adults() {
    $sql = 'SELECT SUM(number_adults_attending) FROM is_nfo_rsvp';
    $result = mysql_query($sql);
    if (!$result) {
        throw new Exception('Failed to get total number of adults attending');
    }

    return mysql_result($result, 0);
}

try {
    $total_adults = get_total_adults();
} catch(Exception $ex) {
    die('Whoops! An error occurred: ' . $ex->getMessage());
    // or even better, add to your template and dump the template at this point
}
// continue code
Ross
A: 

Cool.. I appreciate the link Brabster. phjr's answer is exactly what I was looking for.

Matthew
Try to answer people in their answer's comments section next time. (Just trying to be helpful, not rude.)
yuriks
@yuriks: Remember that users with rep < 50 cannot leave comments.
Bill Karwin
I think they can in their own questions?
OIS