Pagination and loop through total pages count

424 Views Asked by At

I am building a small movie database to learn php. I make a call to the API from The Movie DB:

$url = "https://api.themoviedb.org/3/search/movie?api_key=". $apiKey . "&" . $language . "&query=". $searchTerm ."&". $sortBy .""; // path to your JSON file

The results for the search term brother looks like:

object(stdClass)#2 (4) {
  ["page"]=>
  int(1)
  ["total_results"]=>
  int(1202)
  ["total_pages"]=>
  int(61)
  ["results"]=>
  array(20) {
    [0]=>
    object(stdClass)#3 (14) {
      ["popularity"]=>
      float(18.305)
      ["vote_count"]=>
      int(219)
      ["video"]=>
      bool(false)
      ["poster_path"]=>
      string(32) "/frhzQ5JJ29R3kXuVq3CRYQSczpn.jpg"
      ["id"]=>
      int(327)
      ["adult"]=>
      bool(false)
      ["backdrop_path"]=>
      string(32) "/cL1VX6WllejQQhGTUGGWHW25yor.jpg"
      ["original_language"]=>
      string(2) "en"
      ["original_title"]=>
      string(7) "Brother"
      ["genre_ids"]=>
      array(3) {
        [0]=>
        int(80)
        [1]=>
        int(18)
        [2]=>
        int(53)
      }
      ["title"]=>
      string(7) "Brother"
      ["vote_average"]=>
      int(7)
      ["overview"]=>
      string(613) "Ausgestoßen durch die Bruderschaft seines Yakuza-Clans wird der eiskalte Killer Yamamoto gezwungen, Tokio Richtung Los Angeles zu verlassen. Dort angekommen findet er sich selbst sehr schnell in der alten Routine seines gewalttätigen Tokio Leben wieder. In kürzester Zeit formt er eine neue skrupellos operierende Bruderschaft um sich herum. Macht, Mädchen und Geld liegen im zu Füssen. Aber das ist dem ehemaligen Yakuza Killer Yamamoto nicht genug. Er will alles! Er startet einen blutigen und erbitterten Kampf gegen die Mafia und muss wieder einmal feststellen, dass er von seinen Brüdern verraten wird."

The results show that I am one page 1 of 61 with total results of 1202.

I know that I have to loop through the total_pages but I don't know how to build that query around the API call.

I am thankful for every hint.

1

There are 1 best solutions below

3
On

From their documentation you can see that there is an optional parameter "page". So you can send following requests for each page like:

$url = "https://api.themoviedb.org/3/search/movie?api_key=". $apiKey . "&" . $language . "&query=". $searchTerm ."&". $sortBy . "&page=" . "$pageNumber";