L3 Info : PHP et Applications Web
 
◃  Ch. 5 PDO : PHP Data Object  ▹
 

Binding de variables

Code source

 try {
    include 'dsn.php';

    $dbs2 = $dbh->prepare('SELECT * from auteur WHERE aut_nom = :auteur');
    $auteur = "Dick";
    $dbs2->bindParam(':auteur', $auteur, PDO::PARAM_STR);
    $dbs2->execute();
    $tab = $dbs2->fetchAll($fetch_style = PDO::FETCH_ASSOC );

    afficheTable($tab);

    $dbs3 = $dbh->prepare('SELECT * from auteur WHERE aut_nom LIKE ? OR aut_prenom LIKE ?');
    $dbs3->bindValue(1, "Dick", PDO::PARAM_STR);
    $dbs3->bindValue(2, "Fr%", PDO::PARAM_STR);
    $dbs3->execute();
    $tab = $dbs3->fetchAll($fetch_style = PDO::FETCH_ASSOC );

    afficheTable($tab);

    $dbs4 = $dbh->prepare('SELECT * from auteur WHERE aut_id < 5');
    $dbs4->execute();
    $dbs4->bindColumn(1, $id);
    $dbs4->bindColumn(2, $nom);
    $dbs4->bindColumn('aut_prenom', $prenom);
    while ($ligne = $dbs4->fetch(PDO::FETCH_BOUND)) {
      echo "<p>". $id . " " . $nom . " " . $prenom . "</p>\n";
    }


  } catch (PDOException $e) {
    print "<br />Erreur !: " . $e->getMessage() . "<br/>";
    die();
        }

Résultats

aut_idaut_nomaut_prenom
2DickPhilip K.

aut_idaut_nomaut_prenom
2DickPhilip K.
26HerbertFrank
30PohlFrederik
44LeiberFritz

1 Sutton Jeff

2 Dick Philip K.

3 Kuttner Henry

4 Leinster Murray