Hello, There! Welcome to first post for php beginners. We are going to demonstrate how to use a php to make connection with Mysql database. So, without wasting the time, we’ll start our actual working.
Requirements:
- XAMPP/ WAMP server (download from here: http://www.wampserver.com/en/)
- Notepad++ or any text editor
- php version: 5.6.25 (minimum) separate or integrated in server
Now, we’ve set up an environment. Now we’re ready to go.
First, we should make our database which is an essential part of the database system. All our values will be stored in that. For this tutorial, We are using WAMP server. Start it by simply clicking on the icon. If you’ve not installed it yet, download it from here: http://www.wampserver.com/en/
Go to your browser and type url http://localhost/phpmyadmin/ in the browser. The phpmyadmin page will open. Enter the correct credentials and hit Go. (The default username is “root” and password is “” empty/nothing.)
Now You’ll see the following screen of phpmyadmin.
now,click on the ‘New’ option in the left panel of screen, enter database name as ‘firstdb’ and hit ‘create’. The database will be created with the name ‘firstdb’ (you can see in the left panel). Later we have to make a table in order to save the records. But, we’ll see it in the next tutorials.
Connection code
Now, we comes to the php coding. First of all, create a new File named connect.php and paste the following code in it. Here, we are using the php PDO connection method as it is more secure and helps for exception handling.
<?php $servername = "localhost"; $username = "root"; $password = ""; try { $conn = new PDO("mysql:host=$servername;dbname=firstdb", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
Make sure you have changed the username, database name and password according to your own credentials. Make a new folder inside the www directory say ‘abc’. and save this file in it. Finally, go to url http://localhost/abc/connect.php from the browser and you will see the message “connected successfully”. Congratulations! You’ve successfully setup the database and connected it with php.
Download Source Code
If you have any problems in implementing above tutorial, you can download source code from below link.