0

Possible Duplicate:
PHP PDO bindValue in LIMIT

    $number=8;
    try {  
        $topics=$dbh->prepare("SELECT * FROM topictable ORDER BY RAND() LIMIT ?");
        $topics->execute(array($number));       
        $topicarray = $topics->fetch(PDO::FETCH_BOTH);
        print_r($topicarray);
    }  
    catch(PDOException $e) {  
        echo $e->getMessage();  
    }

Above is my code, I know the problem comes from $topics=$dbh->prepare("SELECT * FROM topictable ORDER BY RAND() LIMIT ?") because when i change ? to 8, it works. Please enlighten me. Thanks.

Community
  • 1
  • 1
Ivan Wang
  • 8,306
  • 14
  • 44
  • 56
  • 1
    Because `LIMIT` cannot be set this way. Also, you have much larger problem in the root of your SQL: [read more here](http://stackoverflow.com/a/9946238/727208) – tereško Jun 09 '12 at 17:25
  • @tereško thanks for your article. However, is there a proper way to pass number to limit in PDO? – Ivan Wang Jun 09 '12 at 17:31
  • Hey @tereško, I modified the codes you given and end up with some new problems. Do you mind come to [here to help me a bit?](http://stackoverflow.com/questions/10963941/sql-getting-8-distinct-random-row-from-a-table-with-two-columns) – Ivan Wang Jun 09 '12 at 19:33

1 Answers1

1
$topics=$dbh->prepare("...LIMIT :limit");
$topics->bindValue(':limit', intval($number), PDO::PARAM_INT);
$topics->execute();
MikeCruz13
  • 1,254
  • 1
  • 10
  • 19
  • you do not need to cast value, if you are binding it as `PDO::PARAM_INT` – tereško Jun 09 '12 at 17:37
  • https://bugs.php.net/bug.php?id=44639 PDO can still be buggy about casting it as a string. better be sure it's an int first. – MikeCruz13 Jun 09 '12 at 17:49
  • "This only happens on emulated parameter binding, i.e. when PDO::ATTR_EMULATE_PREPARES is TRUE.". If you do not know how to properly use PDO, maybe you should read a tutorial. Noone with half-a-brain is using emulated prepares. – tereško Jun 09 '12 at 20:35