mysqli::select_db

mysqli_select_db

(PHP 5, PHP 7)

mysqli::select_db -- mysqli_select_dbクエリを実行するためのデフォルトのデータベースを選択する

説明

オブジェクト指向型

public mysqli::select_db(string $database): bool

手続き型

mysqli_select_db(mysqli $mysql, string $database): bool

データベース接続に対してクエリを実行する際に使用する、 デフォルトのデータベースを設定します。

注意:

この関数は、接続のデフォルトデータベースを変更する際にのみ使用します。 デフォルトデータベースは、mysqli_connect() の 4 番目の引数でも指定可能です。

パラメータ

link

手続き型のみ: mysqli_connect() あるいは mysqli_init() が返す mysqliオブジェクト。

database

データベース名。

返り値

成功した場合に 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.

参考

add a note add a note

User Contributed Notes 2 notes

up
-11
hwalker1 at btopenworld dot com
10 years ago
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.
up
-22
pjasiulewicz at gmail dot com
13 years ago
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.
To Top