PHP PDO – Class prête à l’emploi

class Connexion {
  private $login;
  private $pass;
  private $connec;

  public function __construct($db, $login ='root', $pass=''){
    $this->login = $login;
    $this->pass = $pass;
    try
    {
         $bdd = new PDO(
              "mysql:host=localhost;dbname={$db};charset=utf8mb4", 
               $this->login, 
               $this->pass
      );
      $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
      $bdd->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
      $this->connec = $bdd;
    }
    catch (PDOException $e)
    {
      $msg = 'ERREUR PDO dans ' . $e->getFile() . ' L.' . $e->getLine() . ' : ' . $e->getMessage();
      die($msg);
    }
  }


  public function q($sql,Array $cond = null){
    $stmt = $this->connec->prepare($sql);

    if($cond){
      foreach ($cond as $v) {
        [$key , $value , $type] = $v ;
        $stmt->bindParam($key,$value);
      }
    }

    $stmt->execute();

    return $stmt->fetchAll();
    $stmt->closeCursor();
    $stmt=NULL;
  }

}

Utiliser la class

$db = "first";
$user = "newuser";
$password = "passwor";

$connexion = new Connexion($db, $user, $password);

var_dump($connexion);

var_dump($connexion->q("SELECT * FROM user WHERE id = :id", [ [ "id" , 1, PDO::PARAM_INT ] ]));

Articles incontournables sur le web pour approfondir le sujet :

Cet article a été publié sous la catégorie sql, tutos. Enregistrer cet article permalink.