1

I have a function, which checks a query, and then uses a while loop to extract data, I would like to return this data but I still want it to increment, but I read that return terminates a function, and thus would make it unable to increment. Is there a way around this?

$this->messages = array();
while($row = $data) {
                $this->messages[$i]['id'] = $row['id'];
                $this->messages[$i]['title'] = $row['title'];
                $this->messages[$i]['message'] = $row['message'];
                $i++;

This loop is inside the function, I want to continue until the loop is done, but then I can't return any values.. is there a work around this?

Thank you

EDIT:

<?php

function Message($username){

            $query = "SELECT * FROM msg WHERE `to` = '".$this->userid."' && `to_viewed` = '0' && `to_deleted` = '0' ORDER BY `created` DESC";   
            $stmt = $this->connection->prepare($query);
            $stmt->execute();

    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    $num_rows = $stmt->fetchColumn();

        if($num_rows) {
            $i=0;
            $this->messages = array();
            while($row = $data) {
// want to return these 3 for each result
                $this->messages[$i]['id'] = $row['id'];
                $this->messages[$i]['title'] = $row['title'];
                $this->messages[$i]['message'] = $row['message'];

                $i++;
            }
        } else {
            return 1; 
        }
    }

?>
4

1 回答 1

4

使用PDO::fetchAll(),它返回一个包含所有结果的数组,而不是一次返回一行:

function Message($username){

    $query = "SELECT * FROM msg WHERE `to` = '".$this->userid."' && `to_viewed` = '0' && `to_deleted` = '0' ORDER BY `created` DESC";   
    $stmt = $this->connection->prepare($query);
    $stmt->execute();
    $this->messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $this->messages;
}

但是为了教你循环(一个 CS 101 概念——学习编程的人发生了什么?),下面是你自己编写代码的方法:

    $stmt->execute();
    $this->messages = array();
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC));
        $this->messages[] = $row;
    }
    return $this->messages;
于 2013-08-18T01:58:46.040 回答