PHP: Connect to Mysql Database

This lesson explains how to connect to mysql database through PHP:

mysql_connect is used to connect to the mysql. 


mysql_connect(“localhost”, “root”, “password”) or die(mysql_error());



Here, we have connected to the Mysql server running at “localhost” using “root” as the login and “password” as the password. “localhost” would be replaced by the IP of the server if mysql is running on some other remote machine. If the connection to the server is not made, the script “die” after throwing error on the browser.

 mysql_select_db is used to identidy the database to connect to once the connection is established to Mysql using mysql_connect:


mysql_connect(“localhost”, “login”, “password”) or die(mysql_error());




Here, the database selected is “test_db” after the connection was made. Now, we can query the database “test_db” using php to insert or fetch data from mysql.