プリペアードステートメントの参照

概要

可変パラメータを使用する場合は業務や状況に応じて変化する。パラメータにシングルクォートなどを使用している場合はエラーになるので処理ができるように可変パラメータを自動エスケープする仕組みが必要。


サンプル

ソース

<?php
/*******************************************
 * PDO
 *******************************************/
 
try{
    // MySQLサーバへ接続
    $pdo = new PDO(
        "mysql:host=localhost; dbname=pdotest", 
        "root", 
        "");
var_dump($pdo);
 
    // プリペアードステートメント発行
    $sql = "
    INSERT INTO `cd`(
        id
      , title
      , content) VALUES (
        :id
      , :title
      , :content
      )
    ";
    $stmt = $pdo->prepare($sql);
 
    // bindParamでパラメータ設定(変数未割り当て)
    $stmt->bindParam(":id", $id); 
    $stmt->bindParam(":title", $title); 
    $stmt->bindParam(":content", $content); 
 
    // 変数設定
    $id = 16;
    $title = "HEXDUMP";
    $content = "Hex Dump Music";
 
    // 実行
    $stmt->execute();
 
    $sql = "
    INSERT INTO `cd`(
        id
      , title
      , content) VALUES (
        ?, ?, ?
      )
    ";
    $stmt = $pdo->prepare($sql);
 
    // bindParamでパラメータ設定(変数未割り当て)
    $stmt->bindParam(1, $id); 
    $stmt->bindParam(2, $title); 
    $stmt->bindParam(3, $content); 
 
    // 変数設定
    $id = 17;
    $title = "Mirror";
    $content = "Mirror Music";
 
    // 実行
    $stmt->execute();
 
    // 区切り
    echo "--------------" . PHP_EOL;
 
 
}catch(PDOException $e){
    var_dump($e->getMessage());
}
 
// 切断
$pdo = null;
 
 
 
 



最終更新:2012年12月08日 23:47