insert operation


Now, we need a form to insert records into the table and for that we'll create an insert.php file that will contain an HTML form.

CREATE FORM TO INSERT DATA

<form method="POST" action="insertaction.php">
	<h1><i class="fa fa-user-plus"></i> Register New User</h1>
	<div class="row">
		<div class="col-sm-6">
			<div class="form-group">
				<label>Username</label>
				<input type="text" name="username" class="form-control" required="">
			</div>
			<div class="form-group">
				<label>Email</label>
				<input type="email" name="email" class="form-control" required="">
			</div>
			<div class="form-group">
				<label>Password</label>
				<input type="pasword" name="password" class="form-control" required="">
			</div>
		</div>
		<div class="col-sm-6">	
			<div class="form-group">
				<label>Gender</label>
				<label for=""><input type="radio" name="gender" value="male" checked=""> Male</label>
				<label for=""><input type="radio" name="gender" value="female"> Female</label>
			</div>
			<div class="form-group">
				<label>Language</label>
				<label for=""><input type="checkbox" name="language[]" value="nep" checked=""> Nepali</label>
				<label for=""><input type="checkbox" name="language[]" value="eng"> English</label>
				<label for=""><input type="checkbox" name="language[]" value="oth"> Others</label>
			</div>
			<div class="form-group">
				<label>Country</label>
				<select name="country" class="form-control">
					<option value="nepal">Nepal</option>
					<option value="others">Others</option>
				</select>
			</div>
			<div class="form-group">
				<input type="submit" class="btn btn-sm btn-success" value="Submit">
			</div>
		</div>
	</div>		
</form>

The data will be processed in another page named insertaction.php, then let's create that page and add some processing codes. You can opt to process the form in the same page. In that case, you don't need to add the action attribute in your form tag but instead add the processing php codes in the same page.

FORM DATA PROCESSING USING PHP

<php
// first we can check if the data is being sent
echo '<pre>';
print_r($_POST);

// connection to database retrieved via connect.php
require_once('connect.php');

// now we can remove the previous codes to check data and hold each values in some variables if there is any data being sent from POST method.

if(!empty($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){
	  $user = htmlspecialchars(trim($_POST['username']));
	  $email = $_POST['email'];
	  $password = md5($_POST['password']);
	  $gender = $_POST['gender'];
	  $language = imploade(',',$_POST['language']);
	  $country = $_POST['country'];

	  $query = 
	  "INSERT INTO user_info
	  (username,email,password,gender,language,country) 
	  VALUES 
	  ('$user','$email','$password','$gender','$language','$country')";

	  // to check if the query is correct
	  echo $query;

	  $result = mysqli_query($connect,$query);

	  if($result){
	  	echo 'User data added successfully.';	  	
	  }else{
		echo 'A Problem encountered while adding user data.';
	}
}	

We can encode html special characters and prevent sql injection as well as trim unnecessary spaces with characters if sent via post method. md5 can be used to encrypt password. mysqli_query() asks for two arguments in order to execute any SQL statement; one is the mysqli query while another is the link to database. We created the query here but the database connection link is in connect.php. So, we'll include that file here on the top of the page with require() function so that this file won't work if that file is not present or the details in that page doesn't match to the database.

Everything's perfect as of now but when you refresh the page after some data is inserted to the database, an alert box will appear on top of the page to confirm if you want to resubmit the form data again. If you click yes, the same data will be resubmitted and hence the data will be duplicated in the database. The best solution to this issue is to redirect the user to the same page which will force the paeg to get reloaded and the said alert box won't appear. But, you can't print the success message as stated above after redirecting, instead, you'll need to store the success message in session and display it via session.

HEADER REDIRECT

You can add the header() function to redirect the user back to insert page. In order to display the success or failure message to the user it's always better to use the session. To add message in the session we need to start the session first and rather than using session_start() function in each files, let's add it in the connect.php file. Now, connect.php file will look like this:

<?php
session_start();
define('HOST','localhost');
define('USER','root');
define('PASSWORD','');
define('DB','proceduralphp');

$connect = @mysqli_connect(HOST,USER,PASSWORD,DB);

if(!$connect){
	die ('<h1>Error in establishing Database Connection.</h1>');
}

ADD DATA TO SESSION

Now, we can add message in session from our insertaction file.

<php
require_once('connect.php');

if(!empty($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){
	  $user = htmlspecialchars(trim($_POST['username']));
	  $email = $_POST['email'];
	  $password = md5($_POST['password']);
	  $gender = $_POST['gender'];
	  $language = imploade(',',$_POST['language']);
	  $country = $_POST['country'];

	  $query = "INSERT INTO user_info (username,email,password,gender,language,country) 
	  VALUES ('$user','$email','$password','$gender','$language','$country')";

	  $result = mysqli_query($connect,$query);

	  if($result){
	  	$_SESSION['success_message'] = 'Data inserted successfully';
	  	header('Location: insert.php');
	  	exit();
		}else{
		$_SESSION['error_message'] = 'Error encountered while adding user data';
		header('Location: insert.php');
		exit();
	}
}	

DISPLAY MESSAGE FROM SESSION

Now, again we need to go to the insert file and add these codes on top of the page.

<?php if(isset($_SESSION['error_message'])) : ?>
	<div class="alert alert-danger">
		<= $_SESSION['error_message'] ?>
		<php unset($_SESSION['error_message']); ?>
	</div>
<?php endif: ?>
<?php if(isset($_SESSION['success_message'])) : ?>
<div class="alert alert-success">
	<= $_SESSION['success_message'] ?>
	<php unset($_SESSION['success_message']); ?>
</div>
<?php endif: ?>

UNSET SESSION DATA

Once the session message is displayed, it needs to be destroyed so that it disappears once the page is reloaded. We don't use session_destroy() function at it will destroy all data from the session instead we'll use unset in such cases to remoev specific data value from session.