重写此功能的最有效方法是什么?

时间:2022-09-23 17:09:09
    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).

我知道有一种方法可以用更少的代码来编写它。我只是在寻找最好的方法(不使用像ezSQL这样的东西)。

3 个解决方案

#1


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

#2


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

您可以删除查询的“as number_of_adults”部分并使用mysql_result。

#3


You could also try refactormycode.com

您也可以尝试refactormycode.com

#1


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

#2


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

您可以删除查询的“as number_of_adults”部分并使用mysql_result。

#3


You could also try refactormycode.com

您也可以尝试refactormycode.com