Sunday, May 1, 2011

How To Connect with database in PHP

Hello Friends,
                In previous blog we studied how to create the database in mysql for PHP.In this blog we'll see how to connect with the database in PHP means how to make a connection with our database using PHP.

Simple step to follow for inserting the data in database using PHP.
1.Create A connection with your Database.
2.Fetch the value from the Form using the name property of input.
3.Create the query for insert.
4.Execute(Run) the query.

In this whole blog,we'll use the "StudentMaster" as database and "StudentInfo" as table.And mind the whatever starts with $ sign is variable for temporary use.

So let's start with the first step.

1.Create A Connection With Your Database.
    In this step there are two steps.
    A. Create the connection with MySql server.
           For that there is code of only on line and that is.
            Here $con is variable.We are storing this connection in this variable for further use.
            --"mysql_connect" is mysql function for making connection with MySql server.
            --"localhost" is that where you are running your application.
            --If you are running in your system itself,it will always localhost.
            --"root" is user name.By default when you install the wamp server one user is creates that is root.
            --"" is the password for "root" user. By default is "";
            --Now we have connection with MySql server.
      B.Select your database from MySql server and make connection.
            For that the code is as follows.
                      $db=mysql_select_db("StudentMaster",$con) or die ( mysql_error());
            Here as I explained above $db is just a variable to store the value.
            --"mysql_select_db" is MySql is a function for selecting our database from MySql server.
            --"StudentMaster" is our database name.Type your database name whatever it is.
            --$con is our connection with MySql server as explained above.
            --or is the "or" operator means either left side or right side will run.
            --It means that either "mysql_select_db" will run or "mysql_error()" will run.
            --If "mysql_select_db" fails to run then "mysql_error()" (inbuilt error function of MySql) will run and  tell you the exact error what it is.

Whole code looks like
       $db=mysql_select_db("StudentMaster",$con) or die (mysql_error());

------->How we are connected with the database and ready to use.In next blog we'll learn how to insert data in the database.
------->In this blog if you have any problem or you face any problem while connecting with database let me know.
------->Please leave a comment if it is useful to you.

------->We'll meet soon again.

1 comment:

  1. its a best update
    i like,
    plz update everyday new....
    thnx suman