Insert Complete Form Data in database using PHP with PDO


Create table

CREATE TABLE `userstbl` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `mobile` varchar(15) NOT NULL,
  `emailID` varchar(50) NOT NULL,
  `uesrName` varchar(50) NOT NULL,
  `userpassword` varchar(20) NOT NULL,
  `photo` varchar(50) NOT NULL,
  `gender` varchar(20) NOT NULL,
  `city` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

database.php

<?php
 class dbmodel
 {
    private $dbHost     = "localhost";
    private $dbUsername = "root";
    private $dbPassword = "";
    private $dbName = "jswebsolutions";
	public function __construct()
	{
 		try {
          $conn = new PDO("mysql:host=".$this->dbHost.";dbname=".$this->dbName, $this->dbUsername, $this->dbPassword);
         // set the PDO error mode to exception
          $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          $this->db = $conn;
		  //echo "Connected successfully<br />"; 
            }
          catch(PDOException $e)
            {
             echo "Connection failed: " . $e->getMessage();
            }
	}
 }
?>

    

insert.php

<?php 
include"classCrud.php";
$obj = new Classcrud;
if(isset($_POST['submit'])){
    if(empty($_POST['firstname']) || empty($_POST['mobile']) || empty($_POST['email']) || empty($_POST['gender']) || empty($_POST['city']) || empty($_POST['username']) || empty($_POST['password']) || empty($_POST['repassword'])){
        $err = "please fill all required fields .";
	 }
	else{
	 if($_POST['password'] == $_POST['repassword']){	
	  $filename = basename($_FILES['image']['name']);//echo $file;exit;
		if(empty($filename)){ $filename = "default.jpeg";   }
			 $file = rand(1,1000)."-".$filename;//echo $file;exit;
			 $ext = end(explode('.', $file));//echo $ext;exit; 
			 $file_loc = $_FILES['image']['tmp_name'];//echo $file_loc;exit;
			 $file_size = $_FILES['image']['size']; //echo $file_size;exit;
			 $folder = 'image/';
			 $new_size = $file_size/1024;//echo $new_size;exit;
			 $new_file_name = strtolower($file);
			 $final_file = str_replace(' ','-',$new_file_name);
			  if($ext=="jpg" || $ext=="png" || $ext=="jpeg" ){
				  if($new_size<=500){
					 move_uploaded_file($file_loc,$folder.$final_file);
					 $data = array("name"=>$_POST['firstname'],"mobile"=>$_POST['mobile'],"emailID"=>$_POST['email'],"uesrName"=>$_POST['username'],"userpassword"=>$_POST['password'],"photo"=>$final_file,"gender"=>$_POST['gender'],"city"=>$_POST['city']);
					 $insertResult = $obj->insert("userstbl",$data);
					 if($insertResult != FALSE){
					     header("Location:index.php?success");
					   }
					  else{
					   header("Location:index.php?failed");
					   } 
				  }
				  else{
				   $err = "Image are not upload.";
				  }
			  }
			  else{
			      $err = "Invalid image , image type jpeg , png , jpg are allowed .";
			   }
	  }
	  else{
		   $err = "Password does not match";
		 }
	} 
 }
?>

index.php

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Insert Form data with File Photo using PDO </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<style>
body {padding-top:50px; }
fieldset {border: thin solid #ccc; border-radius: 4px; padding: 20px; padding-left: 40px;
 background: #fbfbfb; }
legend {color: #678; }
.form-control { width: 95%; }
label small { color: #678 !important; }
span.req { color:maroon; font-size: 112%; }
</style>
 <div class="container" ng-app="CRUD" ng-controller="crudController">
	<div class="row">
      <div class="col-sm-12" style="margin-top:-15px; margin-bottom:15px;">
        <h2>Insert Complete Form Data in database using PHP with PDO </h2>
      </div>
      <div class="col-sm-12" style="margin-top:-15px; margin-bottom:15px;">
       <?php 
	    if(isset($_GET['failed'])){
		     ?>
			 <p class="alert alert-danger">Unexpected try again . .</p>
			 <?php
		  }
		   if(isset($_GET['success'])){
		     ?>
			 <p class="alert alert-success">Record insert successfully .</p>
			 <?php
		  }
		 if(isset($err)){
		     ?>
			 <p class="alert alert-danger"><?php echo $err; ?></p>
			 <?php
		   } 
	   ?>
      </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <form id="registrationForm" method="post" action="" role="form" enctype="multipart/form-data">
            <fieldset><legend class="text-center">Valid information is required to register. <span class="req"><small> required *</small></span></legend>
            <div class="form-group"> 	 
                <label for="firstname"><span class="req">* </span> Name: </label>
                    <input class="form-control" name="firstname" id="firstname" type="text" placeholder="First Name"  /> 
                    <div id="errFirst"></div>    
            </div>
            <div class="form-group">
            <label for="phonenumber"><span class="req">* </span> Phone Number: </label>
                    <input type="text" name="mobile" class="form-control phone" placeholder="Mobile Number"/> 
            </div>
            <div class="form-group">
                <label for="email"><span class="req">* </span> Email Address: </label> 
                    <input class="form-control" type="email" name="email" placeholder="Email Address" />   
                        <div class="status" id="status"></div>
            </div>
            <div class="form-group">
                <label for="email"><span class="req">* </span> Gender </label> 
                <div>
                  <input type="radio" name="gender" id="male" value="male" />&nbsp;Male &nbsp;&nbsp; <input type="radio" name="gender" id="female" value="female"/>&nbsp;Female
                </div>       
                        <div class="status" id="status"></div>
            </div>
            <div class="form-group">
                <label for="email"><span class="req">* </span> Select City </label> 
                <div>
                  <select class="form-control" name="city" id="city">
                  <option hidden="hidden">--Select--city--</option>
                    <option value="Kanpur">Kanpur</option>
                      <option value="Lucknow">Lucknow</option>
                        <option value="Banglour">Banglour</option>
                          <option value="Delhi">Delhi</option>
                            <option value="Mumbai">Mumbai</option>
                  </select>
                </div>       
                        <div class="status" id="status"></div>
            </div>
            <div class="form-group">
                <label for="username"><span class="req">* </span> User name:  <small>This will be your login user name</small> </label> 
                    <input class="form-control" type="text" placeholder="User Name" name="username" id="username"/>  
                        <div id="errLast"></div>
            </div>
            <div class="form-group">
                <label for="password"><span class="req">* </span> Password: </label>
                    <input type="password" class="form-control" name="password" id="password" placeholder="Password" /> </p>

                <label for="password"><span class="req">* </span> Password Confirm: </label>
                    <input type="password" class="form-control inputpass" name="repassword" placeholder="Re-type Password" />
                        <span id="confirmMessage" class="confirmMessage"></span>
            </div>
            <div class="form-group">
                <label for="username"><span class="req">* </span> Photo </label> 
                    <input class="form-control" type="file" placeholder="" name="image" id="image" />  
                        <div id="errLast"></div>
            </div>
            <div class="form-group">
                <input class="btn btn-success" type="submit" name="submit" value="Register">
            </div>
            </fieldset>
            </form>
        </div><!-- ends col-6 -->
   </div>
</div>
</body>
</html>
     
    

classCrud.php

<?php
include"database.php"; 
class Classcrud extends dbmodel{
 
  public function insert($tablename,$data_item){
	if(!empty($tablename) && !empty($data_item) && is_array($data_item))
	{
	   $colname = implode(",",array_keys($data_item));
	   $colvalue = implode("','",array_values($data_item));
	   //print_r($colvalue);exit;
	   $sql="INSERT INTO ".$tablename."(".$colname.") VALUES ('".$colvalue."')";
	   //echo $sql;exit;
	   $q = $this->db->prepare($sql);
	   $insert = $q->execute();
		 if(!empty($insert))
		  {
			return TRUE;  
		  }
		  else
		  {
			return FALSE;  
		  }
	}
	else
	{
	  return false;	
	} 
  }	
}
?>