1

I'm getting the following error "PHP Warning: A non-numeric value encountered on line 11". The following code is for a pagination. I have tried everything I know, not sure what else to do. Any help is appreciated.

8 $rowsPerPage = 20;
9 if(isset($_GET['page'])){$pageNum = $_GET['page'];}
10 if(empty($pageNum)) {$pageNum = 1;}
11 $offset = ($pageNum - 1) * $rowsPerPage;
4
  • 1
    $_GET['page'] is probably a string, cast it... or possibly a better approach: $pageNum = (int)!empty($_GET['page']) ? $_GET['page'] : 1; Commented Aug 14, 2018 at 17:23
  • A Warning is not an Error... Commented Aug 14, 2018 at 17:23
  • $pageNum could be a string in line 11 Commented Aug 14, 2018 at 17:23
  • 2
    PHP does not generate warnings when performing math operations on variables containing numerical strings, so $_GET['page'] must contain something non-numbery. Commented Aug 14, 2018 at 17:35

3 Answers 3

3

Something is not numeric (as obvious as that sounds, it is the error) and given you manually set all things to integer other than the GET value, try this:

$rowsPerPage = 20;
if (isset($_GET['page'])) {
    $pageNum = (int) $_GET['page'];
}
if(empty($pageNum)) {
    $pageNum = 1;
}
$offset = ($pageNum - 1) * $rowsPerPage;

Notice the cast to int for the GET param.

You could also just cast to int and PHP will default to integer 0 if it's not already int:

$pageNum = (int) $_GET['page'];

Couldn't help myself - you can also use a ternary to make your setting of the $pageNum cleaner (IMO):

$rowsPerPage = 20;

$pageNum = isset($_GET['page'])
    ? (int) $_GET['page']
    : 1;

$offset = ($pageNum - 1) * $rowsPerPage;
Sign up to request clarification or add additional context in comments.

Comments

2

Seems like $pageNum is non-numeric, i.e. string, try:

$offset = (intval($pageNum) - 1) * $rowsPerPage;

1 Comment

If $pageNum is non-numeric, intval will convert it to zero. Subtracting 1 from 0 will give -1, and multiplying $rowsPerPage by -1 will give you a negative offset, probably not the desired outcome.
2

If $_GET['page'] is non-numeric don't just convert it to an int to get rid of the warning. If it's non-numeric, converting it to a number will prevent the warning, but because non-numeric values will always be converted to zero, your pagination will never work.

If you want your pagination to work properly, you need to handle the warning by discovering why $_GET['page'] is non-numeric and fixing that. Use a debugger or var_dump($_GET['page'] to see what's actually in it. After you find that, you should be able to trace it back to whatever is making the request and correct the error there.

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.