php代码重用。有没有更好的方法呢?

时间:2015-10-03 06:50:37

标签: php code-reuse

我升级了我的代码。在旧代码中,我有两个函数:display_maker_success()display_maker_fail()但我意识到我可以通过在函数中加入更多参数将这两个函数合并为一个display_maker_stat()。我非常喜欢!

更好的方法吗?我想要更多的代码重用。

function display_maker_success($link, $userid){
    $status="closed";
    $result="completed";

    $sql = "select start, name from wuuk where tasker_id ='$userid' and status ='$status' and result ='$result' order by id desc LIMIT 6;";

    $result = mysql_query($sql, $link);
    $isempty=mysql_num_rows($result);
    If ($isempty ==0) {
        echo "No Record";
    } else {
        echo "<table border=1>";
        echo "<tr><th>Date & Time</th><th>Name</th><th>Status</th></tr>";
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
            echo "<tr><td>$row[0]</td><td>$row[1]</td><td>Completed</td></tr>";
        };
        echo "</table>";
    };
};

function display_maker_fail ($link, $userid) {
    $status="closed";
    $result="fail";

    $sql = "select start, name from wuuk where tasker_id ='$userid' and status ='$status' and result ='$result' order by id desc LIMIT 1;";
    $result = mysql_query($sql, $link);
    $isempty=mysql_num_rows($result);
    If($isempty ==0){
        echo "No Record";
    } else {
        echo "<table border=1>";
        echo "<tr><th>Date & Time</th><th>Name</th><th>Status</th></tr>";
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
            echo "<tr><td>$row[0]</td><td>$row[1]</td><td>fail</td></tr>";
        };
        echo "</table>";
    };
};

function display_maker_stat ($link, $userid, $reuslt, $limit) {
    $status="closed";
    $result="fail";

    $sql = "select start, name from wuuk where tasker_id ='$userid' and status ='$status' and result ='$result' order by id desc LIMIT 1;";
    $result = mysql_query($sql, $link);
    $isempty=mysql_num_rows($result);
    If($isempty ==0){
        echo "No Record";
    } else {
        echo "<table border=1>";
        echo "<tr><th>Date & Time</th><th>Name</th><th>Status</th></tr>";
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
            echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$result</td></tr>";
        };
        echo "</table>";
    };
};

1 个答案:

答案 0 :(得分:3)

尝试下面的内容,

此外,您的代码中的错误很少,我已经纠正了它们。

function display_maker_stat($link, $userid, $reuslt = 'fail', $limit)
{
    $status = "closed";
    $html = '';
    $sql = "select start, name from wuuk where tasker_id ='$userid' and status ='$status' and result ='$result' order by id desc LIMIT 1;";
    $query = mysql_query($sql, $link);
    if (mysql_num_rows($query) != 0) {
        $html .= "<table border=1>";
        $html .= "<tr><th>Date & Time</th><th>Name</th><th>Status</th></tr>";
        while ($row = mysql_fetch_array($query, MYSQL_NUM)) {
            $html.= "<tr><td>$row[0]</td><td>$row[1]</td><td>$result</td></tr>";
        }
        $html.= "</table>";
        echo $html;
    }
    else {
        echo "No Record";
    }
}

了解OOP