Sunday, July 6, 2014

How to insert data into database ?

In our previous section, we show you how to connect to database in php. In this post, we will show you how to insert data into database. require 'connect.php'; imports the php file which has been already defined. Its demo is shown here. The $_POST['username'] and  $_POST['password'] takes value of input value in html form. Then, "if($u_pass !=
$u_repass)" checks if the password entered twice matches or not. If matches, it proceeds, else print error message "password didnot match". Then the query is executed in storing value in 'login' table in "first_name" and "password" columns. Below is a php code for storing data
require 'connect.php';
if(isset($_POST['username']) && isset($_POST['password']))
    {
        $u_name = $_POST['username'];
        $u_pass = $_POST['password'];
        $u_repass = $_POST['repassword'];
        if($u_pass != $u_repass){
           echo 'Password didnot match';
        }else
            {
                if(!empty($u_name)&&!empty($u_pass)){
                     $query = "INSERT INTO `login`(`first_name`,`password`) VALUES ('$u_name','u_pass')";
                     if($query_run = mysql_query($query)){
                          echo 'successfully inserted';
                     }else{
                          echo 'could not insert';
                          }
                }else {
                     echo 'Please fill all the required inputs first.';
                }
          }
  }

No comments:

Post a Comment