Note that in the second example, if the database "world" does not exist, the database selected does not change. You may need to add additional code to ensure that you are connected to the correct database.
(PHP 5, PHP 7)
mysqli::select_db -- mysqli_select_db — クエリを実行するためのデフォルトのデータベースを選択する
オブジェクト指向型
$database
): bool手続き型
データベース接続に対してクエリを実行する際に使用する、 デフォルトのデータベースを設定します。
注意:
この関数は、接続のデフォルトデータベースを変更する際にのみ使用します。 デフォルトデータベースは、mysqli_connect() の 4 番目の引数でも指定可能です。
成功した場合に true
を、失敗した場合に false
を返します。
例1 mysqli::select_db() の例
オブジェクト指向型
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* 現在のデフォルトデータベース名を取得します */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
/* データベースを world に変更します */
$mysqli->select_db("world");
/* 現在のデフォルトデータベース名を取得します */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
手続き型
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "test");
/* 現在のデフォルトデータベース名を取得します */
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Default database is %s.\n", $row[0]);
/* データベースを world に変更します */
mysqli_select_db($link, "world");
/* 現在のデフォルトデータベース名を取得します */
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Default database is %s.\n", $row[0]);
上の例の出力は以下となります。
Default database is test. Default database is world.
Note that in the second example, if the database "world" does not exist, the database selected does not change. You may need to add additional code to ensure that you are connected to the correct database.
In some situations its useful to use this function for changing databases in general. We've tested it in production environment and it seams to be faster with switching databases than creating new connections.