In this article we’ll try to achieve three things:
1) Connect to MySQL using PHP
2) Create a database and table in MySQL
3) Connect to MySQL using PHP and fetch / retrieve data from the database
Scope of this article is to guide beginners who have just started PHP programming and have never tried to connect to any database using PHP, although PHP have the capability to connect to MySQL, MySQLi, PostGRESQL, Oracle and other number of databases today we’ll only discuss about PHP and MySQL connectivity and the development environment considered is XAMPP on Windows.
Connect to MySQL using PHP
Though there are a number of ways to connect to MySQL using PHP, in this article we’ll only talk about the most basic method using mysql_connect function. This function returns a resource which is a pointer to the database connection also called a database handle. Below is a sample PHP code to connect MySQL hosted within XAMPP on Windows where database username is root, password is blank or empty, and hostname is localhost. If you are using a Linux server those three values may or may not be same depending upon your MySQL database location and MySQL user configuration. Create a file under your folder Bittu (refer to the previous post) called mysql_test.php, copy and paste the below code into the file and save.
<?php $db_username = "root"; $db_password = ""; $db_hostname = "localhost"; //connection to the database $db_resource = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); echo "Connected to MySQL<br>"; //close the connection mysql_close($db_resource); ?>
Remember to close the connection after you’re done with the job, otherwise multiple connections will be kept open and take up resources which in turn may cause the program or server to hang or even create a deadlock. mysql_close is required to be used only when we are using mysql_connect.
Now if you run this script on browser (type the following in your browser’s address bar http://localhost/Bittu/mysql_test.php), you should see the desired output:
Connected to MySQL
This way we have successfully connected to MySQL using PHP but so far we not tried to fetch / retrieve data from the database but before we fetch we need have some data in the database, in the next step I’m going to explain you the same.