MySQL Select Database - Choose database to use

Before we can actually start to run queries on our database from within PHP, we need to connect to the MySQL server and select the database that we will be running the queries on. Usually, there are more than one databases that are running on a database server and that is why we need to explicitly choose the database that we want to work with.

To connect to the MySQL server, we will need to make use of the mysql_connect function. The tutorial below explains.

PHP mysql_connect Syntax - Connect to a MySQL Database

Below is the syntax for the mysql_connect function.

mysql_connect(server, username, password); 

The function may take additional parameters as well, but these are the standard parameters and should work in most cases.

The server parameter refers to the hostname of the MySQL server, a domain name that resolves to its IP address, or the IP address of the server.

The username parameter is simply the name of the user (that has appropriate permissions) that you will be using to connect to the particular database.

The password parameter should be the password of the particular user that you are using to connect to the database.

Note that you would have to have already set up a database with a user with these particular credentials before trying to connect to the database from PHP.

PHP mysql_select_db Syntax - Choose a MySQL Database

In its simplest form, this is what we use to select the appropriate database on our database server:

mysql_select_db($database_name);

The $database_name variable is a variable which stores a string containing the name of the database we want to use.

PHP mysql_select_db Example - Choose a MySQL Database

Here is a complete example of connecting to the MySQL server and selecting the database that we want to use:

<?php
 
// specifies the name of the database we will be choosing
$database_name = 'tutorials';
 
// we must have an open connection before we can select a database
$connection = mysql_connect('localhost', 'user1', 'letmein');
 
mysql_select_db($database_name);
 
// do some actions on the database
 
// close the database when we are finished
mysql_close($connection);
 
?>

That is it! We hope this MySQL tutorial taught you a thing or two about connecting to MySQL and selecting databases from within your PHP script. No you can go on to running a MySQL Query in PHP.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...