Search code examples
phppreparepdo

PHP PDOStatement prepare and bindValue methods


why doesn't below code work ?

 $pdo = new PDO('mysql:dbname=_test;host=localhost','root', '');
 $select=$pdo->prepare("SELECT * FROM test WHERE th=:name");
 $select->bindValue(":name","1");
 print_r($select);

when i print $select it results :

 PDOStatement Object ( [dbh] => PDO Object ( ) [queryString] => SELECT * FROM test   WHERE th=:name )

thanks!


Solution

  • You should add error handling to your database calls, for example by setting up PDO to throw exceptions.

    Your current problem is that you don't actually execute() the statement:

    $select->bindValue(":name","1");
    $select->execute();
    

    After that you would need to fetch() results from the result set to actually see the values in your database:

    while ($row = $select->fetch()) {
      // do something with the data
    }
    

    Edit: To enable exceptions in PDO (you don't have to catch them just yet, the system will throw unhandled exception errors):

    $pdo = new PDO('mysql:dbname=_test;host=localhost','root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));