02 June 2011

Creating a connection to MySQL in PHP - Php For Beginners - Lesson 11

Whenever we want to access the data in the mysql database using php, we have to create a connection to that particular database. Once the connection is establish we can insert and retrieve any data from the mysql database.

Creating a Mysql connection is quite simple in php, a simple built-in php function "mysql_connect()" is used for this purpose.

Syntax:
mysql_connect(servername,username,password); 
Where servername is the name of the server to connect, username and password are the credentials used to connect to the database.

Selecting a Database:
Once a connection is established to the database, we have to select the particular database that we want to use for inserting and fetching the data. This can be done by using another built-in php function "mysql_select_db()".
Syntax:
mysql_select_db(database,connection)
Where database is the name of the database and connection is the connection created in the earlier part of this article.

Working Example:
Since connecting and selecting the database is required each time we want to use a database. So we can save the code for creating the connection and selecting the database in a file and include it wherever we want to use the database. You can name that file as "connection.php" or whatever other name you want. Contents of this file are as follows:
<?php
$db_host="localhost";
$db_user="root";
$db_pass="";
$db_name="any_db";

$con=mysql_connect($db_host,$db_user,$db_pass) or die ('Can not connect to database');
mysql_select_db($db_name,$con) or die ('Can not Select Database');
?>
If you are using this code on the local server then the above mentioned configuration will work fine, as the default host/server name is always "localhost", user name is always "root" and password is always "" for the local server, but if you are using it on some web server then you have to change these settings to your web server's settings. The db_name is the name of the database that you want to select.

Well I guess this is all for this lesson, for any queries, should you have, feel free to comment and ask.

next Previous Lesson

No comments: