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, PHP 8)
mysqli::select_db -- mysqli_select_db — Legt die standardmäßige Datenbank für Datenbankabfragen fest
Objektorientierter Stil
Prozeduraler Stil
Wählt die Datenbank aus, die standardmäßig bei Abfragen über die Datenbankverbindung verwendet werden soll.
Hinweis:
Diese Funktion sollte nur verwendet werden, um die Standard-Datenbank für die Verbindung zu ändern. Die Standard-Datenbank kann mit dem 4. Parameter in mysqli_connect() ausgewählt werden.
mysql
Nur bei prozeduralem Aufruf: ein von mysqli_connect() oder mysqli_init() zurückgegebenes mysqli-Objekt.
database
Der Name der Datenbank
If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR
) and the requested operation fails,
a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT
,
a mysqli_sql_exception is thrown instead.
Beispiel #1 mysqli::select_db()-Beispiel
Objektorientierter Stil
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* Ermitteln des Namens der aktuellen Standard-Datenbank */
$Ergebnis = $mysqli->Abfrage("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Die Standard-Datenbank ist %s.\n", $row[0]);
/* Standard-Datenbank auf "world" ändern */
$mysqli->select_db("world");
/* Ermitteln des Namens der aktuellen Standard-Datenbank */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Die Standard-Datenbank ist %s.\n", $row[0]);
Prozeduraler Stil
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "test");
/* Ermitteln des Namens der aktuellen Standard-Datenbank */
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Die Standard-Datenbank ist %s.\n", $row[0]);
/* Standard-Datenbank auf "world" ändern */
mysqli_select_db($link, "world");
/* Ermitteln des Namens der aktuellen Standard-Datenbank */
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Die Standard-Datenbank ist %s.\n", $row[0]);
Die obigen Bespiele erzeugen folgende Ausgabe:
Die Standard-Datenbank ist test. Die Standard-Datenbank ist 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.