PHP mysqli select_db() Method
The PHP mysqli::select_db() / mysqli_select_db() function is used to select the default database to be used when performing queries against the database connection.
Note: This function should only be used to change the default database for the connection. It can also be selected using default database as fourth parameter in mysqli_connect() function.
Syntax
//Object-oriented style public mysqli::select_db(database) //Procedural style mysqli_select_db(mysql, database)
Parameters
mysql |
Required. For procedural style only: Specify a mysqli object returned by mysqli_connect() or mysqli_init(). |
database |
Required. Specify the database name. |
Return Value
Returns true on success or false on failure.
Example: Object-oriented style
The example below shows the usage of mysqli::select_db() method.
<?php //establishing connection to the database $mysqli = new mysqli("localhost", "user", "password", "myDb1"); if ($mysqli->connect_errno) { echo "Connection error: ". $mysqli->connect_errno; exit(); } //getting the name of the current default database $result = $mysqli->query("SELECT DATABASE()"); $row = $result->fetch_row(); printf("Default database is %s.\n", $row[0]); //changing default database to "myDb2" $mysqli->select_db("myDb2"); //getting the name of the current default database $result = $mysqli->query("SELECT DATABASE()"); $row = $result->fetch_row(); printf("Default database is %s.\n", $row[0]); //closing the connection $mysqli->close(); ?>
The output of the above code will be:
Default database is myDb1. Default database is myDb2.
Example: Procedural style
The example below shows the usage of mysqli_select_db() function.
<?php //establishing connection to the database $mysqli = mysqli_connect("localhost", "user", "password", "myDb1"); if (mysqli_connect_errno()) { echo "Connection error: ". mysqli_connect_errno(); exit(); } //getting the name of the current default database $result = mysqli_query($mysqli, "SELECT DATABASE()"); $row = mysqli_fetch_row($result); printf("Default database is %s.\n", $row[0]); //changing default database to "myDb2" mysqli_select_db($mysqli, "myDb2"); //getting the name of the current default database $result = $mysqli->query("SELECT DATABASE()"); $row = $result->fetch_row(); printf("Default database is %s.\n", $row[0]); //closing the connection mysqli_close($mysqli); ?>
The output of the above code will be:
Default database is myDb1. Default database is myDb2.
❮ PHP MySQLi Reference