how can i return multiple database record from a c

2019-09-06 13:29发布

问题:

Lets say i have a class like this

class book {
    public $title;
    public $author;
    public $page_num;
        .....
        ....

 public function show_book($limit=1){
         .... 
        $result = mysql_query("SELECT title,author,page_num  FROM book limit=$limit");

         while($row = mysql_fetch_array($result))
          {
         $this->title=$row['title'];
         $this->author=$row['author'];
         $this->page_num=$row['page_num'];
          }

        }

and then i can use it like :

 $book = new book();
 $book->show_book();
 echo $book->title." ".$book->author ...... ;

this works for one book what if i want to show 7 books ? this is not working for $book->show_book($limit=7); i can make 7 objects but i think there's a better way

回答1:

I'd rename the function show_books and have it return an array of book objects. When you have no matches you return an empty array, otherwise you return all of the matching elements. It probably makes the most sense as a static method rather than an instance method.

public static function show_books($limit=1){
     .... 
    $result = mysql_query("SELECT title,author,page_num  FROM book limit=$limit");
    $books = array();

     while($row = mysql_fetch_array($result))
     {
          $book = new book();
          $book->title=$row['title'];
          $book->author=$row['author'];
          $book->page_num=$row['page_num'];
          $books[] = $book;
     }
     return $books;
}

$books = Book::show_books(7);


回答2:

The class book represents one book (as the name suggests).

So it would be better if your move the show_books() method from this class to another place.

Now, you can modify it to return an array of the found books: In the while loop you need to create new book objects for each record you get from the query.