Sunday 25 November 2012

Php code to insert values into database

Here it is a sample code to insert elements into database.

Inserting elements into database is a simple task, but before performing this task we should be connected with database and so on.

How to get connected with database using php?

Here in this case with are opting MySQL as the database, world's largest open source database. Connection is like this:

         $con=mysql_connect('[Host]','[username]','[password]') or die ('Connection failed');
         Format is like this.

<?php
        $con=mysql_connect('localhost','root','') or die ('Connection failed');
?>

This will connect you to the database, if not it will prompt you an error message 'Connection failed'. And our task is to insert data on to database.

<?php
        mysql_connect_db('db_name',$con) or die('Connection to database failed');
                                                                //Set database connection.
                                                                //Say 'db_name' as database name.
?>

Insert values to database:

<?php
      $sql_insert="insert into <table_name> values (field1,field2) values ('val1','val2')";
      $result      =mysql_query($sql_insert);
?>

Thank You!


No comments:

Post a Comment