Saturday, July 5, 2008

To connect to a mysql database from php

Connect to a mysql database from php
for beginners

//Define variable//
//starting by assigning the address of server, username, and also password
//"127.0.0.1" or "localhost" means that mysql database is installed on the machine where it will connected by php.
$servername = "127.0.0.1";

//the default username for mysql database server is "root".
$username = "root";

//the default password for mysql database is "".
$password = "";

// Declare connection //
//use mysql_connect to make a connection to the mysql server
$dbconnect = mysql_connect($servername,$username,$password);

//test if $dbconnect return successful connection.
if (!$dbconnect){
print "There are some error connecting to database";
}

//select the database which you want to use. Here, i'll illustrate database selection named mydatabase.
$select = mysql_select_db("mydatabase");

//test if $select for database return successful selection.
if (!$select){
print mysql_error()."
\n";
}

Another way is to create a function call "connectit()" which can be access anytime from any page. Remember to define the variable $servername, $username, and $password in order to use the connectit() function.

function connectit(){
//connect to mydatabase
global $servername, $username, $password;
$dbconnect = mysql_connect($servername, $username, $password);
if (!$dbconnect){
print "there are some problem connecting to database...";
}
$select = mysql_select_db("mydatabase");
if (!$select){
print mysql_error()."
\n";
}
return $dbconnect;
}

mysql_close() is adviseable to be used to close a connection at the last action after connected to mysql database. eg.
mysql_close($dbconnect);

0 comments: