Tuesday, May 20, 2008

Database Connectivity 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.

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.

//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.

Executing a query

To execute a query you’ll have to create table in your database and fill it with some data. Let’s say we have table named ‘Customers’ with next fields: Name, Address, Phone. What we want to do is simply to display all data stored in this table.





What have we done here? First line defines sql string which will get our data. You can get a lot of different data by simply changing sql string. If statement in second line verifies if there are any results returned by sql str. This line is optional but I like to use it so it won’t come to unexpected errors. While loop in 3rd line loops through data record set we received with our sql query. If there is 10 records in the table, while loop would repeat 10 times and output the code between its tags. The code between while tags will be repeated and outputted.

That’s it. You only need this code and you’ll have your first database driven application. Hope this tutorial helped you.

No comments: