Select MySQL Database using PHP
Once a connection with a database server is established, it may be required to select a particular database. This is required because a database server may contain multiple databases and you can work with a single database at a time.
Along with this, to connect to the MySQL server, mysqli_connect() function can be used. After establishing the connection, mysql_select_db() function can be used to select the default database to be used when performing queries against the database connection.
Select a MySQL Database - Object-oriented style
The example below demonstrates how to select the default database in object-oriented style.
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDb1"; //establishing connection $mysqli = new mysqli($servername, $username, $password, $dbname); //checking connection if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: ". $mysqli->connect_error; 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.
Select a MySQL Database - Procedural style
To obtain the same result using procedural style, the following script can be used.
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDb1"; //establishing connection $mysqli = mysqli_connect($servername, $username, $password, $dbname); //checking connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: ". mysqli_connect_error(); 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.
Complete PHP MySQLi Reference
For a complete reference of all properties, methods and functions of PHP MySQLi extension, see PHP MySQLi Reference.
❮ PHP & MySQL