Now we are going to know how to connect to MySQL database using a PHP script. First of all, you have to know that PHP is working well and your first PHP page is ok. Second, you have to check if MySQL server is working well also, and that could be easily by using any DB browser such as MySQL Front or PHP MyAdmin. Third, you can write the following code and see the result:
If you get no error, and you get a blank white page then the connection is ok. And if you need to get an error message you can use the following code:
mysql_connect("servername","username","password") or die ("Server Error");
mysql_select_db("database_name") or die ("Database Error");
While if you need a successful connection message, you can use the following code:
In this example, my server is "localhost" and the username is "root"
$con = mysql_connect("localhost","root","");
print "Successfully connected to the server";
// My database name is "abc"
$db = mysql_select_db("abc");
print "Successfully connected to the database";
- You can use mysql_pconnect() instead of mysql_connect()
- Do not forget to close the connection at the end of the page using