Php/docs/mysqli.examples-basic

提供:Dev Guides
< Php
移動先:案内検索

MySQLi 拡張機能の基本的な例

ここで示す例は、接続し、クエリを実行し、基本的なエラー処理を行い、 結果の行を出力し、MySQL データベースから切断するまでの方法を示しています。

この例は [http://dev.mysql.com/doc/sakila/en/index.html » dev.mysql.com, as described here] からダウンロードでき、フリーで利用できる Sakila データベースを使っています。 この例を動作させるためには、(a) sakila をインストールする か、(b) 接続のための変数(ホスト名、 ユーザ名、パスワード)を書き換えるかしてください。

例1 MySQLi 拡張機能のおおまかな使用例

<?php// Let's pass in a $_GET variable to our example, in this case// it's aid for actor_id in our Sakila database. Let's make it// default to 1, and cast it to an integer as to avoid SQL injection// and/or related security problems. Handling all of this goes beyond// the scope of this simple example. Example://   http://example.org/script.php?aid=42if (isset($_GET['aid']) && is_numeric($_GET['aid'])) {    $aid = (int) $_GET['aid'];} else {    $aid = 1;}// sakila という名前の MySQL データベースを選択肢、接続します。// ホスト名: 127.0.0.1, ユーザ名: your_user, パスワード: your_pass, db: sakila$mysqli = new mysqli('127.0.0.1', 'your_user', 'your_pass', 'sakila');// あらやだ! connect_errno が存在するので、接続に失敗したようです!if ($mysqli->connect_errno) {    // 接続に失敗しました。何をしたいですか?    // あなた自身に問い合わせを投げる(emailで?) か、エラーをロギングするか、    // ナイスなページを表示するなど、ですね。    // 秘密の情報を晒したくはありませんよね    // 次を試してみてください    echo "Sorry, this website is experiencing problems.";    // 公開されているサイトでやるべきではありませんが、    // 次の例でとりあえず示すのは、MySQL エラー関連情報です -- ロギングしたいかもしれまえせん。    echo "Error: Failed to make a MySQL connection, here is why: \n";    echo "Errno: " . $mysqli->connect_errno . "\n";    echo "Error: " . $mysqli->connect_error . "\n";        // 何かナイスなものを表示したら、単純に exit します。    exit;}// SQLクエリを実行します。$sql = "SELECT actor_id, first_name, last_name FROM actor WHERE actor_id = $aid";if (!$result = $mysqli->query($sql)) {    // あらやだ! クエリが失敗しちゃいました。    echo "Sorry, the website is experiencing problems.";    // Again, do not do this on a public site, but we'll show you how    // to get the error information    // 再度になりますが、これを公開されているサイトでやってはいけませんが、    // とりあえずエラー情報を取得する方法を示します。    echo "Error: Our query failed to execute and here is why: \n";    echo "Query: " . $sql . "\n";    echo "Errno: " . $mysqli->errno . "\n";    echo "Error: " . $mysqli->error . "\n";    exit;}// やりました。MySQLへの接続とクエリに成功しました。// さて、結果はあるのでしょうか?if ($result->num_rows === 0) {    // あらやだ! 行がなありません。これが期待通りで、OKの場合もありますし、    // そうでない場合もあります。この場合は、actor_id が大きすぎることにしましょうか?    echo "We could not find a match for ID $aid, sorry about that. Please try again.";    exit;}// この例では、結果が一行しかないことを知っていることにします。// よって、それを連想配列で取得しましょう。連想配列のキーは、テーブルのカラム名です。$actor = $result->fetch_assoc();echo "Sometimes I see " . $actor['first_name'] . " " . $actor['last_name'] . " on TV.";// さて、5つのランダムな actor を取得し、名前を一覧にして出力しましょう。// ここでは、あなたが自分で追加できるように、エラーハンドリングを少し少なくしておきます。$sql = "SELECT actor_id, first_name, last_name FROM actor ORDER BY rand() LIMIT 5";if (!$result = $mysqli->query($sql)) {    echo "Sorry, the website is experiencing problems.";    exit;}// actor ごとにリンクを追加しつつ、5人の actor をランダムに一覧にして出力します。echo "<ul>\n";while ($actor = $result->fetch_assoc()) {    echo "<li><a href='" . $_SERVER['SCRIPT_FILENAME'] . "?aid=" . $actor['actor_id'] . "'>\n";    echo $actor['first_name'] . ' ' . $actor['last_name'];    echo "</a></li>\n";}echo "</ul>\n";// The script will automatically free the result and close the MySQL// connection when it exits, but let's just do it anyways// スクリプトは終了する時に自動で結果を解放し、MySQL 接続を閉じますが、// ここではそれをとにかくやってみましょう。$result->free();$mysqli->close();?>