将变量参数传递给方法

时间:2015-06-09 04:02:13

标签: php mysql

我使用下面的方法来获取消息(我不使用SELECT *就像问题那样写了它)。有时我只需要10条消息,有时我需要所有消息。完成这样的事情的最佳方法是什么?

public function receivedMessages($user_id) {
    if($q = $this->db->mysqli->prepare("SELECT * 
                                        FROM messages 
                                        WHERE receiver_id = ? 
                                        LIMIT 10"))
    {
        $q->bind_param("i", $user_id);

        $q->execute();

        $rows = $this->helperClass->bindResults($q);
        $q->close();

        return $rows;
    }
        return false;
}

3 个答案:

答案 0 :(得分:1)

只需使用其他variable -

public function receivedMessages($user_id, $limit = false) {
    $qry = "SELECT * FROM messages WHERE receiver_id = ?";
    if(!empty($limit)) {
        $qry .= " LIMIT $limit"; // If limit passed then add limit statement to query
    }
    if($q = $this->db->mysqli->prepare($qry))
    {
        $q->bind_param("i", $user_id);

        $q->execute();

        $rows = $this->helperClass->bindResults($q);
        $q->close();

        return $rows;
    }
        return false;
}

答案 1 :(得分:0)

public function receivedMessages($user_id,$num_0f_messages) {

if($num_of_messages === 0)){

//select all
} else {

if($q = $this->db->mysqli->prepare("SELECT * 
                                    FROM messages 
                                    WHERE receiver_id = ? 
                                    LIMIT ?"))
{
    $q->bind_param("ii", $user_id, $num_of_messages);

    $q->execute();

    $rows = $this->helperClass->bindResults($q);
    $q->close();

    return $rows;
}
    return false;
} 
}

要获取所有消息,请执行receivedMessages(1,0) ; 限制消息,仅说5个结果集,receivedMessages(1,8)

答案 2 :(得分:0)

您可以根据评论

尝试此解决方案
public function receivedMessages($user_id,$limit=0) {

if($limit==0){
   $sql="SELECT * FROM messages WHERE receiver_id = ?";
} else {
   $sql="SELECT * FROM messages WHERE receiver_id = ? LIMIT $limit";
}

if($q = $this->db->mysqli->prepare($sql))
    {
        $q->bind_param("i", $user_id);

        $q->execute();

        $rows = $this->helperClass->bindResults($q);
        $q->close();

        return $rows;
    }
        return false;
}