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.
|
<?php 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:
|
<?php mysql_connect("localhost", "login", "password") or die(mysql_error()); mysql_select_db("test_db"); ?>
|
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.

Recent comments
22 weeks 4 days ago
23 weeks 1 day ago
23 weeks 1 day ago
23 weeks 4 days ago
24 weeks 1 day ago
26 weeks 2 days ago
29 weeks 2 days ago
32 weeks 1 day ago
32 weeks 6 days ago
33 weeks 5 days ago