Page 1 of 1

How can use trim in the given code? And the below is not run

Posted: Tue Feb 23, 2016 3:25 am
by Rameshwar
THE CODE IS IN ADD_QUESTION PAGE(add_question.php)

Code: Select all

<?php
session_start();
$rep_char = array("&", "*", "^", "(", ")", "%","=", ";", "\\", "\"", "'", "<", ">", "?", " AND ", " and ", " OR ", " or ", "WFXSSProbe", "wfxssprobe");
$sub="";
if(isset($_POST['qst_insert']))
{
	$sub=strip_tags($_POST['qst_insert']);
	$sub=str_replace($rep_char,"",$sub);
}
if($sub=='submit'){
//print_r($_POST);
$array_item[0]=strip_tags($_POST['subname']);
$array_item[1]=strip_tags($_POST['addque']);
$array_item[2]=strip_tags($_POST['optA']);
$array_item[3]=strip_tags($_POST['optB']);

$array_item[4]=strip_tags($_POST['optC']);
$array_item[5]=strip_tags($_POST['optD']);
$array_item[6]=strip_tags($_POST['anstrue']);	 
$array_item[7]=strip_tags($_POST['mark']);
$array_item[8]=strip_tags($_POST['lod']);
$array_item[9]=strip_tags($_POST['status']);
/******************Prevent SQL Injection**********************/
$i=0;
while($i<=9){
	  $array_item[$i]=str_replace($rep_char,"",addslashes(strtoupper($array_item[$i])));
	  $i=$i+1;
}
/******************Server Side Validation**********************/
$i=0;
while($i<=9){
	  if($array_item[$i]=="")
		  $errorFlag=1;
	  $i=$i+1;
}
/******************Ebd of Server Side Validation**********************/;
//$question=$array_item[0];
//$oprionA=$array_item[1];
?>
<html>
	<head>
	<script type="text/javascript">
		function validate(){
			if(document.add_question.subname.value=="-1"){
				alert("Choose Subject");
				document.add_question.subname.focus();
				return false;
			}
			if(document.getElementById("addque").value==null || document.getElementById("addque").value==""){
				alert("Please Enter Question");
				document.add_question.addque.focus();
				return false;
    		} 
			if(document.add_question.optA.value == ""){
				alert("Please Enter Option A");
				document.add_question.optA.focus();
				return false;
			}
			if(document.add_question.optB.value == ""){
				alert("Please Enter Option B");
				document.add_question.optB.focus();
				return false;
			}
			if(document.add_question.optC.value == ""){
				alert("Please Enter Option C");
				document.add_question.optC.focus();
				return false;
			}
			if(document.add_question.optD.value == ""){
				alert("Please Enter Option D");
				document.add_question.optD.focus();
				return false;
			}
			if( document.add_question.anstrue.value == "-1" ){
				alert( "Choose Correct Answer" );
				document.add_question.anstrue.focus();
				return false;
   			}
			if( document.add_question.mark.value == "-1" ){
				alert( "Choose Suitable Mark" );
				document.add_question.mark.focus();
				return false;
   			}
			if( document.add_question.lod.value == "-1" ){
				alert( "Select level of difficulty" );
				document.add_question.lod.focus();
				return false;
   			}
			return( true );
		}
		</script>
	</head>
<body>
<form class="form-horizontal" name="add_question" action="insert.php" method="post" onSubmit="return validate();">
							<input type="hidden" name="action" value="qst_insert"/>
								<fieldset>
									<!-- Subject Name-->
									<div class="form-group">
										<label class="col-md-3 control-label" for="name">Subject Name</label>
										<div class="col-md-9">
											<select class="form-control" name="subname" id="subname">
												<option value="-1" selected>--- Select ---</option>
												<option value="English">English</option>
												<option value="Bengali">Bengali</option>
												<option value="Mathmatics">Mathmatics</option>
												<option value="General Knowledge">General Knowledge</option>
											</select>
										</div>
									</div>
									<!-- Question body -->
									<div class="form-group">
										<label class="col-md-3 control-label" for="message">Question</label>
										<div class="col-md-9">
											<textarea class="form-control" id="addque" name="addque" placeholder="Please enter question here..." rows="5"></textarea>
										</div>
									</div>
									<div class="form-group">
										<label class="col-md-3 control-label" for="name">Option A</label>
										<div class="col-md-9">
										<input id="name" name="optA" type="text" placeholder="Enter Option A" class="form-control">
										</div>
									</div>
									<div class="form-group">
										<label class="col-md-3 control-label" for="name">Option B</label>
										<div class="col-md-9">
										<input id="name" name="optB" type="text" placeholder="Enter Option B" class="form-control">
										</div>
									</div>
									<div class="form-group">
										<label class="col-md-3 control-label" for="name">Option C</label>
										<div class="col-md-9">
										<input id="name" name="optC" type="text" placeholder="Enter Option C" class="form-control">
										</div>
									</div>
									<div class="form-group">
										<label class="col-md-3 control-label" for="name">Option D</label>
										<div class="col-md-9">
										<input id="name" name="optD" type="text" placeholder="Enter Option D" class="form-control">
										</div>
									</div>
									<!--CORRECT ANSWER-->
									<div class="form-group">
										<label class="col-md-3 control-label" for="name">Correct Answer</label>
										<div class="col-md-9">
											<select class="form-control" name="anstrue" id="anstrue">
												<option value="-1" selected>Choose Correct Answer</option>
												<option value="A">A</option>
												<option value="B">B</option>
												<option value="C">C</option>
												<option value="D">D</option>
											</select>
										</div>
									</div>
								
									<!-- Subject Name-->
									<div class="form-group">
										<label class="col-md-3 control-label" for="name">Mark</label>
										<div class="col-md-9">
											<select class="form-control" name="mark" id="mark">
												<option value="-1" selected>Choose Mark</option>
												<option value="1">1</option>
												<option value="2">2</option>
												<option value="3">3</option>
												<option value="4">4</option>
												<option value="5">5</option>
											</select>
										</div>
									</div>
									<!-- Subject Name-->
									<div class="form-group">
										<label class="col-md-3 control-label" for="name">Difficulty Level</label>
										<div class="col-md-9">
											<select class="form-control" name="lod" id="lod">
												<option value="-1" selected>Rate Level of difficulty</option>
												<option value="1">1</option>
												<option value="2">2</option>
												<option value="3">3</option>
												<option value="4">4</option>
												<option value="5">5</option>
											</select>
										</div>
									</div>
									<!-- Subject Name-->
									<div class="form-group">
										<label class="col-md-3 control-label" for="name">Status</label>
										<div class="col-md-9">
											<select class="form-control" name="status" id="status">
												<option value="1" selected>1</option>
												<option value="0">0</option>
											</select>
										</div>
									</div>
									
									
									
									<!-- Form actions -->
									<div class="form-group">
										<div class="col-md-12 widget-right">
											<button type="submit" class="btn btn-default btn-md pull-right" style="color: #333333; background-color: #0099CC; width: 100px;" name="submit">ADD</button>
										</div>
									</div>
								</fieldset>
							</form>
</body>

IN (insert.php) PAGE
<?php
	include("database.php");
	if(isset($_POST['action']) && $_POST['action'] == 'qst_insert')
	{
	$inssql = "INSERT INTO question SET
			subject_name = '".$_POST['subname']."',
			question = '".$_POST['addque']."',
			option_a = '".$_POST['optA']."',
			option_b = '".$_POST['optB']."',
			option_c = '".$_POST['optC']."',
			option_d = '".$_POST['optD']."',
			correct_option = '".$_POST['anstrue']."',
			mark = '".$_POST['mark']."',
			difficulty_level = '".$_POST['lod']."',
			status = '".$_POST['status']."'"; 
			$insqry = mysqli_query($l,$inssql);
			if($insqry)
			{
				echo "Sucessful Insertion";
			}
			else
			{
				echo "Failed to Insert";
				header("location: add_question.php");
			}
}
?>
PLEASE GIVE MY WHOLE COMPLETE ANSWER....
OR MAIL ME TO rameshwar129@gmail.com

Re: How can use trim in the given code? And the below is not

Posted: Tue Feb 23, 2016 7:24 am
by Celauran
Where are you looking to use trim? What isn't working?

Re: How can use trim in the given code? And the below is not

Posted: Wed Feb 24, 2016 1:06 am
by Rameshwar
I cannot understand where to place "trim" in the code, so that i can avoid the entry of space.
The given php code in the "add_question.php" page, i cann't understand where to place, i will place in the "insert.php" page or in the add_question.

Re: How can use trim in the given code? And the below is not

Posted: Wed Feb 24, 2016 7:42 am
by Celauran
You're passing $_POST values directly into your query, so you'd technically need to call trim() there. However, passing $_POST values into your query directly is generally a bad idea as it leaves you vulnerable to SQL injection. Use prepared statements instead.

Re: How can use trim in the given code? And the below is not

Posted: Wed Feb 24, 2016 5:12 pm
by Christopher
More messy form code. It is difficult to see what is going on in this code because:

1. the Presentation code is mixed in with the Domain code (MVC are all mixed in one script).
2. There is a lot of duplication and redundant code.

So first separate the Presentation and Domain code. To do that, put all the the HTML/Javascript in a template file: templates/add_question.php

The rest is spread across two pages: add_question.php and insert.php. There the idea of separation between the Controller code and the Model code is here, but the separation is not clean.

Code: Select all

// THIS IS THE CONTROLLER CODE
// Session never used. This can be removed.
session_start();

// Why are we cleaning the Submit for variable. We are not using its value and we only care that it is set. 
$rep_char = array("&", "*", "^", "(", ")", "%","=", ";", "\\", "\"", "'", "<", ">", "?", " AND ", " and ", " OR ", " or ", "WFXSSProbe", "wfxssprobe");
$sub="";
if(isset($_POST['qst_insert']))
{
	$sub=strip_tags($_POST['qst_insert']);
	$sub=str_replace($rep_char,"",$sub);
}
if($sub=='submit'){
// All of the below filtering and validation can be done in one loop.
$array_item[0]=strip_tags($_POST['subname']);
$array_item[1]=strip_tags($_POST['addque']);
$array_item[2]=strip_tags($_POST['optA']);
$array_item[3]=strip_tags($_POST['optB']);

$array_item[4]=strip_tags($_POST['optC']);
$array_item[5]=strip_tags($_POST['optD']);
$array_item[6]=strip_tags($_POST['anstrue']);	 
$array_item[7]=strip_tags($_POST['mark']);
$array_item[8]=strip_tags($_POST['lod']);
$array_item[9]=strip_tags($_POST['status']);
/******************Prevent SQL Injection**********************/
$i=0;
while($i<=9){
	  $array_item[$i]=str_replace($rep_char,"",addslashes(strtoupper($array_item[$i])));
	  $i=$i+1;
}
/******************Server Side Validation**********************/
$i=0;
while($i<=9){
	  if($array_item[$i]=="")
		  $errorFlag=1;
	  $i=$i+1;
}
/******************Ebd of Server Side Validation**********************/;
//$question=$array_item[0];
//$oprionA=$array_item[1];

// HERE IS THE VIEW CODE
include 'templates/add_question.php';

#IN (insert.php) PAGE

// HERE IS THE MODEL CODE
	include("database.php");
	if(isset($_POST['action']) && $_POST['action'] == 'qst_insert')
	{
// ACTUALLY THE MODEL CODE STARTS HERE. SHOULD BE A CLASS.
	$inssql = "INSERT INTO question SET
			subject_name = '".$_POST['subname']."',
			question = '".$_POST['addque']."',
			option_a = '".$_POST['optA']."',
			option_b = '".$_POST['optB']."',
			option_c = '".$_POST['optC']."',
			option_d = '".$_POST['optD']."',
			correct_option = '".$_POST['anstrue']."',
			mark = '".$_POST['mark']."',
			difficulty_level = '".$_POST['lod']."',
			status = '".$_POST['status']."'"; 
			$insqry = mysqli_query($l,$inssql);

// BUT THIS IS MORE CONTROLLER CODE
			if($insqry)
			{
// AND THIS IS ANOTHER TEMPLATE
				echo "Sucessful Insertion";
			}
			else
			{
				echo "Failed to Insert";
				header("location: add_question.php");
			}
}
?>
OK, now refactor the code:

Code: Select all

$errorMsg = '';
$isSubmitted = isset($_POST['qst_insert']) && ($_POST['qst_insert'] == 'submit');
if($isSubmitted){
	$rep_char = array("&", "*", "^", "(", ")", "%","=", ";", "\\", "\"", "'", "<", ">", "?", " AND ", " and ", " OR ", " or ", "WFXSSProbe", "wfxssprobe");
	$fields = array('subname', 'addque', 'optA', 'optB', 'optC', 'optD', 'anstrue', 'mark', 'lod', 'status', );
	$data = array();
	$errors = array();
	foreach ($fields as $field) {
		if (isset($_POST[$field]) && $_POST[$field]) {
			$data[$field] = $_POST[$field];
			$data[$field] = strip_tags($data[$field]);
			$data[$field] = trim($data[$field]);			// ACTUAL ANSWER TO QUESTION ;)
			$data[$field] = str_replace($rep_char, "", addslashes(strtoupper($data[$field])));
		} else {
			$errors[$field] = $field;
		}
	}

	if ($errors) {
		$errorMsg = "Missing field: " . implode(',', $errors);
	}
}

if ($isSubmitted) {
	if ($errorMsg == '') {

// START MODEL CODE
// THIS CODE SHOULD BE PUT IN A CLASS
		include("database.php");

		$inssql = "INSERT INTO question SET ";
		foreach ($data as $key => $value) {
			$insql .= "$key=?, ";
		}
		$stmt = mysqli_prepare($l, $inssql);
		call_user_func_array(array($stmt, "bind_param"), $data);		// Why PDO is nicer!
		$result = mysqli_stmt_execute($stmt);
// END MODEL CODE

		if ($result) {
			header("location: add_question_success.php");
			exit;
		}
	}
}
include 'templates/add_question.php';