0

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

2
  • You've got no WHERE clause, so I'd guess that you only have one record in the BOOK table... Commented Nov 14, 2010 at 22:27
  • Why, oh why, have you got public fields?! If you are going to use OOP, please don't break encapsulation. Commented Nov 14, 2010 at 22:39

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.