Skip to content

Instantly share code, notes, and snippets.

@taitokiss
Created November 27, 2016 01:18
Show Gist options
  • Save taitokiss/9e695c260b17c21f0ee91a9c65aa8187 to your computer and use it in GitHub Desktop.
Save taitokiss/9e695c260b17c21f0ee91a9c65aa8187 to your computer and use it in GitHub Desktop.
PDOを用いた処理1(基本)
<?php
$dsn = 'mysql:host=localhost;dbname=uriage;charset=utf8';
$user = 'testuser';
$password = 'testuser';
// 例外処理
try{ // 例外が発生するおそれがあるコード
// PDOクラスのオブジェクトを作成
$dbh = new PDO($dsn, $user, $password);
// データベース操作
$sql = 'select id, name from shouhin';
// SELECT文を実行
$sth = $dbh->query($sql);
// 連想配列を取得
while($result = $sth->fetch(PDO::FETCH_ASSOC)){
echo "id=" . $result['id'];
echo ",name=" . $result['name'].'<br>';
}
// データベースへの接続を閉じる
$dbh = null;
}catch (PDOException $e){ // 例外発生時の処理
die("Error:" . $e->getMessage());
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment