Skip to content

Instantly share code, notes, and snippets.

@katsube
Created December 19, 2020 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katsube/2197c700d668332b6576f37c1b9c2d83 to your computer and use it in GitHub Desktop.
Save katsube/2197c700d668332b6576f37c1b9c2d83 to your computer and use it in GitHub Desktop.
<?php
/**
* MySQLに接続しデータを取得する
* (エラー処理対応版)
*
*/
//-------------------------------------------------
//準備
//-------------------------------------------------
$dsn = 'mysql:dbname=rpgdb;host=localhost'; //接続先
$user = 'senpai'; //MySQLのユーザーID
$pw = 'indocurry'; //MySQLのパスワード
// 実行したいSQL
$sql = 'SELECT * FROM Monster';
//-------------------------------------------------
//SQLを実行
//-------------------------------------------------
try{
$dbh = new PDO($dsn, $user, $pw); //接続
$sth = $dbh->prepare($sql); //SQL準備
$sth->execute(); //実行
//取得した内容を表示する
while(true){
//ここで1レコード取得
$buff = $sth->fetch(PDO::FETCH_ASSOC);
if( $buff === false ){
break; //データがもう存在しない場合はループを抜ける
}
// 表示
printf("%d: %s\n", $buff['id'], $buff['name']); //$buffには連想配列として格納されている
};
}
catch( PDOException $e ) {
printf("[Error] %s¥n", $e->getMessage());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment