Friday, 10 February 2012

Database Connectivity (PHP + MySql)

Before you can access data in a database from your web application, you must create a connection to the database.

Creating a database connection with PHP is very simple and can be done by using the following code.

<?
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
 $dbservertype='mysql';
 $servername='127.0.0.1';
 $dbusername='username';
$dbpassword="password";
 $dbname='databasename';
 connecttodb($servername,$dbname,$dbusername,$dbpassword);
function connecttodb($servername,$dbname,$dbuser,$dbpassword)
{
global $link;
$link=mysql_connect ("$servername","$dbuser","$dbpassword");
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
}
?>


replace username with the user of the database, password with the password for that user and databasename with the name of the database for which you want to make the connection.
(for eg: if the username is nickhalden, password is nikkie and database name is project then the lines would be
$dbusername='nickhalden';
$dbpassword='nikkie';
$dbname='project';
)

No comments:

Post a Comment