Sunday, September 25, 2011

// // Leave a Comment

Database Connection With PHP


This tutorial will help you make connection to your database with PHP. It’s very simple process but I know how difficult can be for someone who is only starting to learn PHP. To test this example you should download and install Apache server, MySQL database server and PHP. You can find detailed guide and all mentioned components here.

Creating config.php

If you want to use a database in your application, you have to make config.php file which will contain basic database data. Here we will declare database path, username, password, database name and create connection string. We’ll make local database connection for a start. Put the code below into config.php file and put it in the root folder of your project.
<?php
$host = "localhost"; //database location
$user = "bitis"; //database username
$pass = "kaka"; //database password
$db_name = "bitis"; //database name
//database connection
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db_name);
//sets encoding to utf8
mysql_query("SET NAMES utf8");
?>
First 4 lines are basic database data. 2 lines below is connection string which connects to server and then mysql_select_db selects database. The last line is optional but I like to include it to be sure the data will be in utf8 format. Now we have config.php file created and saved in the root folder of our project.

Include config.php in application

Don’t be distracted with me calling website an application. I call it because you can use this methods in any application. It doesn’t necessarily has to be a website.
To include config.php into application (lets say it’s a website) simply put next line on the top of the source code of index.php.
<?php include 'config.php'; ?>

That’s it. You only need this code and you’ll have your first database driven application. Hope this tutorial helped you.
If you know a better way of doing this, post it in a comment.

0 comments:

Post a Comment