Question

<?php
try
{
    $db = new PDO("mysql:host=localhost;dbname=DBNAME", "USER", "PASSWD");

    $stmt = $db->prepare("SELECT id, name FROM testdb ORDER BY time DESC LIMIT :index, 10");
    $stmt->bindValue(":index", $_GET['index'], PDO::PARAM_INT);
    $stmt->execute();

    while( $r = $stmt->fetch(PDO::FETCH_ASSOC) )
    {
        echo var_dump($r);                                      
    }

}
catch( PDOException $e )
{
    die("Exception");
}

The problem is on this line: $stmt->bindValue(":index", $_GET['index'], PDO::PARAM_INT);

And the specific parameter is the second one.

The code as it is above doesn't work, it doesn't return anything so the while loop isn't executed. If I replace $_GET['index'] with a number, like 10, it works just fine, it returns 10 rows. Echoing $_GET['index'] displays a number, so it should pass a number. I've also tried bindParam, but the result is same.

Why isn't this working?

EDIT:

Interesting... If I replace $_GET['index'] with (int)$_GET['index'] it works.

Was it helpful?

Solution

If you check $stmt->errorInfo() you will actually find that your query failed.

PDO::PARAM_INT tells PDO that you are giving it an integer. If you do not give PDO an integer, PDO will quote the value in the sql string.

SELECT id, name FROM testdb ORDER BY time DESC LIMIT "1", 10

All values in $_GET are either an array or a string. You did the correct thing by coercing $_GET['index'] to an integer before binding it as a value. By doing this, PDO gets an integer, was expecting an integer from PDO::PARAM_INT, and therefore will not quote the value in the sql string.

SELECT id, name FROM testdb ORDER BY time DESC LIMIT 1, 10

OTHER TIPS

Values in the $_GET super-global array are strings : PHP doesn't guess what's passed iin the querystring.


If you want one value from $_GET to be considered as an integer -- which is what you want, here -- you'll need to convert it to an integer yourself.

In order to do that, you can use :

  • A typecast : (int)$_GET['yourval']
  • The intval() function, which allows one to specific the base that's to be used

Sounds like $_GET['index'] is not what you expect it to be. Use var_dump() to inspect the value closer. Pay attention to the length of the string that var_dump reports, because some characters are not visually detectable, but the length of the string will tell the hidden story.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top