Reputation: 89
I need get method but not working
my code :
<?php
$page = $_GET['page'] ? intval($_GET['page']) : 1;
echo "current page : ".$page."<br/>";
?>
and
$page's result is 1. but i try www.example.com/test.php?page=3
$page's result is still output 1.
Why is this happening?
Upvotes: 1
Views: 66
Reputation: 1455
At first you should check if is page
setted, then you can access page
try this:
if(isset($_GET['page'])){
$page = $_GET['page'] ? intval($_GET['page']) : 1;
echo "current page : ".$page."<br/>";
}
here is the result i am getting:
Upvotes: 5
Reputation: 598
$page = $_GET['page'] ? intval($_GET['page']) : 1;
Is the short form for
if($_GET['page'] !== null){ $page = intval($_GET['page']); }else{ $page = 1; }
So there are at least two sources of error. "$_GET['page']" could be unset resulting in 1. If this was the case there would also be an error cause of the unknown variable.
It could be a string which is casted to 1 - in this case there is no error thrown.
For your needs it makes more sense to check for an existing variable like mrustamzade proposed.
I would also check for a number like this
if(isset($_GET['page']) && is_numeric($_GET['page'])){
$page = intval($_GET['page']);
}else{ $page = 1; }
echo "current page : ".$page."<br/>";
Upvotes: 1
Reputation: 2200
You can just modify the statement,
$page = $_GET['page'] ? intval($_GET['page']) : 1;
to
$page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
Hope this helps.
Upvotes: 1