Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
appfog mysql 接続の仕方
<?php
// 環境変数参照
$vcap_services = getenv( 'VCAP_SERVICES' );
if ( $vcap_services === false ) {
exit();
}
// 環境変数からDB設定を取得
$vcap_services_json = json_decode( $vcap_services );
$db = $vcap_services_json->{"mysql-5.1"}[0]->credentials;
// DB接続
$pdo = null;
try {
$pdo = new PDO(
"mysql:host={$db->host};port={$db->port};dbname={$db->name}",
$db->username,
$db->password,
array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET CHARACTER SET utf8"
)
);
} catch (Exception $e) {
//print_r( $e );
exit();
}
// ダミーテーブル作成
echo "ダミーテーブル作成\n";
$sql = "CREATE TABLE dummy ( id mediumint not null, name varchar(10), primary key(id) )";
$params = array();
$stmt = $pdo->prepare( $sql );
$stmt->execute($params);
// ダミーデータinsert
echo "ダミーデータinsert\n";
$sql = "INSERT INTO dummy (id, name) VALUES (:id1,:name1), (:id2,:name2)";
$params = array(
'id1' => 1, 'name1' => 'ムグお',
'id2' => 2, 'name2' => 'ムグおじさん',
);
$stmt = $pdo->prepare( $sql );
$stmt->execute($params);
// select実行
echo "select実行\n";
$sql = "SELECT * FROM dummy ORDER BY id";
$params = array();
$stmt = $pdo->prepare( $sql );
$stmt->execute($params);
$results = $stmt->fetchAll( PDO::FETCH_ASSOC );
// 表示
echo "表示\n";
print_r( $results );
// ダミーテーブル削除
echo "ダミーテーブル削除\n";
$sql = "DROP TABLE dummy";
$params = array();
$stmt = $pdo->prepare( $sql );
$stmt->execute($params);
echo "END\n";
ダミーテーブル作成
ダミーデータinsert
select実行
表示
Array
(
[0] => Array
(
[id] => 1
[name] => ムグお
)
[1] => Array
(
[id] => 2
[name] => ムグおじさん
)
)
ダミーテーブル削除
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.