I'm using the following code to paginate mysql results using this tutorial https://www.youtube.com/watch?v=6SuCSIJ5wNU.
Eventhough the code is working perfectly, i get an undefined variable. ": Undefined variable: pagination in ".
<?php
$get_data = $connect -> query("SELECT NULL FROM movies"); // get the table in the database
$row_count = $get_data -> rowCount(); // count rows
// pagination starts
if( isset($_GET['page']) ) {
$page = preg_replace("#[^0-9]#", "", $_GET['page']);
} else {
$page = 1;
}
$perPage = 2;
$lastPage = ceil($row_count / $perPage);
if($page < 1) {
$page = 1;
} else if($page > $lastPage) {
$page = $lastPage;
}
$limit = "LIMIT ".($page - 1) * $perPage . ", $perPage";
if($lastPage != 1) {
if($page != 1) {
$prev = $page - 1;
$pagination.='<a href="index.php?page='.$prev.'">Previous</a>';
}
if($page != $lastPage) {
$next = $page + 1;
$pagination.='<a href="index.php?page='.$next.'">Next</a>';
}
}
?>
You never defined $pagination
before you started appending to it (.=
).
These two are equivalent:
$foo .= 'bar';
$foo = $foo . 'bar';
To do the concatentation, PHP has to retrieve the value of $foo
, which hasn't been defined, so you get your warning. Then the concatenation occurs and is stored in $foo
, so the error doesn't occur again the next time you try it.