How to Connect to a MySQL Database Using PHP



PHP


To connect to a database in MySQL from PHP, the following code to do so is:

This is done by the mysql_connect function shown below:



where servername is the address of the server where the MySQL database is located, username is the user name to log into this MySQL server, and password is the password that allows access to this MySQL server.

How to Connect to the MySQL Server

To connect to the MySQL server, not database, just the server, the line of code that allows us to make this connection is:

mysql_connect($servername, $username, $password);

This line of code above connects to the MySQL server. This is how connection to the MySQL server is established.

How to Connect to a Database

Once we connect to the desired MySQL server, we now can connect to the database in this server that we desire to connect to.

We connect to the desired database in MySQL by adding the following line to the above code:

@mysql_select_db($database) or die("Unable to select database");

The @mysql_select_db($database) function selects the database that is desired to be connected to, where $database is the variable that contains the name of the database.

Output if Successfully Connected to Database

If the line:

Connected to MySQL Database

is shown, you have successfully connected to the database in the MySQL database.

This is because PHP will only reach the echo function if there were no errors in any of the above lines.

HTML Comment Box is loading comments...