Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /home/users/1/juny/web/hidef/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /home/users/1/juny/web/hidef/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524

[PHP] PDOでMySQLの接続確認をする

公開日: : PHP


Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /home/users/1/juny/web/hidef/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524

PDO

PHPでMySQLに接続する際には、mysql_connect関数を使用せずにPDO(PHP Data Objects)で接続します。
※mysql_connect関数はPHP5.5.0から非推奨
※PDOはPHP5.1以降から標準で利用可能

サンプルソース

以下、接続例です。
接続結果は簡単なメッセージとして、htmlに出力するようにします。

<?php
$connect = true;
$host = 'localhost';
$db_name = 'sample-db';
$user = 'root';
$password = 'root';
$message = '';
try {
	$dbh = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8", $user, $password);
} catch (PDOException $e) {
	$connect = false;
	exit('Database connection failure ' .$e->getMessage());
	$message .= 'Database connection failure ' .$e->getMessage() .'';
}
if ($connect) {
	$message .= 'Database connection success!';
}
$dbh = null;
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>DB ACCESS TEST</title>
</head>
<body>
	<p><?php echo $message; ?></p>
</body>
</html>

9行目で接続処理をします。文字コードはDBの設定に合わせてください。
18行目でMySQLの切断処理をします。
※切断処理は記述しなくてもガベージコレクタによって自動的に切断されます。

ad

関連記事

[PHP] curl転送してみる(googleに)

curlでgoogle画像検索APIにアクセスしてみます。 curlとは...  取得す

記事を読む

[PHP] ランダムな英数字を生成する

便利系メソッド 今回はPHPでランダムな英数字を作成してみます。 function get_

記事を読む

ad

Message

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

ad

[PHP] curl転送してみる(googleに)

curlでgoogle画像検索APIにアクセスしてみます。 cu

[PHP] PDOでMySQLの接続確認をする

PDO PHPでMySQLに接続する際には、mysql_connec

[PHP] ランダムな英数字を生成する

便利系メソッド 今回はPHPでランダムな英数字を作成してみます。

[Swift] プロパティリスト(plist)の値を取得

plistからデータを取得してみます。 こちらのエントリーも参考にし

[Swift] Asset Catalogについて

XCode5から追加されたAsset Catalog。 いままで標準

→もっと見る

  • 1978年の七夕生まれ。 25才でweb業界の門を叩き、28才でフリーランスに。 現在は、フリーランスでマークアップ中心に、wordpressのカスタマイズやデザインをしております。 また、iPhoneアプリの開発もしております。

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /home/users/1/juny/web/hidef/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524
PAGE TOP ↑

Warning: Use of undefined constant user_level - assumed 'user_level' (this will throw an Error in a future version of PHP) in /home/users/1/juny/web/hidef/wp-content/plugins/ultimate-google-analytics/ultimate_ga.php on line 524