Created
December 19, 2020 06:51
-
-
Save katsube/2197c700d668332b6576f37c1b9c2d83 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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