0
0

More than 1 year has passed since last update.

$stmt = $pdo->queryと$stmt = $pdo->prepareの違いについて

Posted at

queryとprepareについて勉強したため、

皆さんに共有する。

$stmt = $pdo->queryは一番簡単な方法
$stmt = $pdo->prepareは「 query 」に手間をかけてバリデーションをして手間を行う方法。

queryを使う場合

 try {
    // データを取得するSQL
    //tasksテーブルのid,titleの取得の準備し、表示させる。
    $stmt = $pdo->query("SELECT id, title FROM tasks");

    全ての行をまとめて取り出し、「$titlessに格納する
    $titless = $stmt->fetchAll(PDO::FETCH_ASSOC); 

  } catch(PDOException $e) {
    // エラーメッセージを出力
    echo $e->getMessage();
  } finally {

    // データベースの接続解除
    $pdo = null;
  }

確認する
prepare使う場合

  try {
    // データを取得するSQL
    //tasksテーブルに入っているidを:id,titleを:titleに格納する
    $stmt = $pdo->prepare("SELECT id=:id, title=:title FROM tasks");


    ※※ーー上記id=:id 」:idを下記の:idに入り $idに格納するーー※※


    //上記で格納した:idを$id :titleを$titleにバインドパラムする
    $stmt->bindParam(':id'   , $id,    PDO::PARAM_INT);
    $stmt->bindParam(':title'   , $title,    PDO::PARAM_STR);

    //sqlを実行し、$resに格納する。
    $res = $stmt->execute();


    //title全てを抽出し、$titlessに入れる
    $titless = $stmt->fetchAll(PDO::FETCH_ASSOC);  

    } catch(PDOException $e) {
    // エラーメッセージを出力
        echo $e->getMessage();
    } finally {
    // データベースの接続解除
    $pdo = null;
    }

で実施する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0