LoginSignup
14
13

More than 5 years have passed since last update.

PDOを使用する(mysql)

Last updated at Posted at 2015-03-23

PDOでDB接続用の関数connection.phpと実際に処理をする(ここではDBにデータ挿入する)sample.phpに分けて、使用する例。

connection.php
function db_connection(){
    //DBのユーザ
    $db_user = "root";
    //DBのパスワード
    $db_password = "xxxxxxxxxx";
    //ホスト
    $db_host = "localhost";
    //接続するDBの名称
    $db_name = "xxxxxx";
    //接続するDBタイプ(他にpgsql,sqliteなどがある)
    $db_type = "mysql";

    //接続のための情報
    $dsn = "$db_type:host=$db_host;dbname=$db_name;charset=utf8";

try{
    //PDOによる接続
    $dbh = new PDO($dsn, $db_user, $db_password);
    //属性の設定(接続エラーが発生したら例外を投げる設定)
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //属性の設定(プリペアドステートメントの使用)
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
    //エラーが発生したらメッセージを表示して終了
    die("エラー内容:".$e->getMessage();)
}
return $dbh;
}
sample.php
//DB接続用の関数を読み込み
require_once("connection.php");

//関数使用
$dbh = db_connection();

$name = "guest";
$age = 20;
$sex = "male";

try{
    //トランザクションを開始
    $dbh->beginTransaction();

    //データ挿入のsqlをプレースホルダで組み立てる(あくまで例)
    $sql = "insert into user (name, age, sex) values (?, ?, ?)"
    //sql文を実行する準備
    $stmt = $dbh->prepare($sql);
    //プリペアドステートメントの実行
    $stmt->execute(array($name, $age, $sex));
    //トランザクションをコミット。ここで、変更が確定
    $dbh->commit();

}catch(PDOException $e){
    //エラー発生して例外が投げられたら、ロールバックする
    $dbh->rollback();
    print "エラー内容:".$e->getMessage();
}
14
13
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
14
13