Friday, August 3, 2012

Connect with the PHP MySQL Database



You must create a connection to the database, Than  you can access data in a database. In PHP, it is done with the function name  mysql_connect() .

// mysql_connect("servername","username","password");

Q.What is "servername"?
Ans= It is Optional. Specifies the server to connect to.And the Default value is "localhost".

Q.What is "username"?
Ans= It is Optional.Specifies the username to LOGIN with. The Default value is the name of the User that owns the server process.

Q.What is "password"?
Ans=  It is Optional. Specifies the password to LOGIN with. Default value is "  ". That means NULL.


------------------------------------------------------------------------------
Total code 
------------------------------------------------------------------------------

<?php

session_start();

$connect = mysql_connect("localhost","mint_php","MeHeDi");

//server="localhost" userName= "mint_php " pass=" MeHeDi "

if (!$connect)

  {

  die('Could not connect: ' . mysql_error());

  }
// Here you can write your code

?>
---------------------------------------------------------- 




If it is need then at first  we should start the session. By using  session_start()  function.

// session_start() ;

Remember if you start a session than one time you should destroy the Session. By using  
session_destroy()  function. 

// session_destroy();

We learn about the Session in another Post. 
Here we use a variable ( $connect) to store the connection in this variable for later use in our script.

And the "die " part will be executed if the connection fails.


In the "die" part i use  mysql_error()
The  mysql_error() function return the error description of the last MySQL operation.
This function return an empty string [ "" ] If there are no error occurs.

No comments:

Post a Comment