Search code examples
phpmysqlpdoprepare

PDO query returning False half the time


I have a problem with PDO mysql queries

HEre is my simple code (not a real situation just to show you the problem)

$connexion = new PDO(SQL_DSN, SQL_USERNAME, SQL_PASSWORD);
$stmt = $connexion->prepare('SELECT * from missions,platforms WHERE missions_platforms_id = exl_platforms_id AND missions_id = :mission');
$stmt->execute(array(":mission" => '1'));
$ligne = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($stmt);

$stmt = $connexion->prepare('SELECT * from missions,platforms WHERE missions_platforms_id = exl_platforms_id AND missions_id = :mission');
var_dump($stmt);
$stmt = $connexion->prepare('SELECT * from missions,platforms WHERE missions_platforms_id = exl_platforms_id AND missions_id = :mission');
var_dump($stmt);

and the output :

object(PDOStatement)[2]
 public 'queryString' => string 'SELECT * from missions,platforms WHERE missions_platforms_id = platforms_id AND missions_id = :mission' (length=122)

boolean false

object(PDOStatement)[2]
 public 'queryString' => string 'SELECT * from missions,platforms WHERE missions_platforms_id = platforms_id AND missions_id = :mission' (length=122)

Why the 2nd var_dump return false ?

If I do more times the same schema it is returning false half the time...

Thanks you


Solution

  • Try to close your result set cursor after reading the result set with PDOStatement::fetch() using PDOStatement::closeCursor() such as:

    $connexion = new PDO(SQL_DSN, SQL_USERNAME, SQL_PASSWORD);
    $stmt = $connexion->prepare('SELECT * from missions,platforms WHERE missions_platforms_id = exl_platforms_id AND missions_id = :mission');
    $stmt->execute(array(":mission" => '1'));
    $ligne = $stmt->fetch(PDO::FETCH_ASSOC);
    var_dump($stmt);
    $stmt->closeCursor();
    
    $stmt = $connexion->prepare('SELECT * from missions,platforms WHERE missions_platforms_id = exl_platforms_id AND missions_id = :mission');
    var_dump($stmt);
    $stmt = $connexion->prepare('SELECT * from missions,platforms WHERE missions_platforms_id = exl_platforms_id AND missions_id = :mission');
    var_dump($stmt);
    

    The first statement is the only statement you actually fetch a result from.