Server side validation for PHP form

I'm usingPHP 4.3.10 and MySQL.

I have try different ways to validate this form (server side), with no succes.

I need to verify that the num field is not empty and display a message if it's empty.
And saving the result in db only if num field have a value.
For now there is only javascript validation and I don't want to rely on it.

<?php
require_once('_header2.php');

if (isset($r_expiration)) {
  set_config('expiration', $r_expiration);
  set_config('num', $r_num);
  save_config();
  redirect('index.php');
  die();
} //if

$expiration = get_config('expiration');
$num = get_config('num');
?>

<head>
</head>

<body>                 
<form name=frm method=POST onsubmit="return allow_submit()">
<input type=text name=expiration size=10 value="<?php echo $expiration; ?>">
<input type=text name=num size=10 value="<?php echo $num; ?>">
<input type=submit name=btn_submit value="Save"> 
</form>     

Open in new window

Thanks
LVL 28
lenamtlAsked:
Who is Participating?
 
Mark BradyConnect With a Mentor Principal Data EngineerCommented:
Oh sorry! What a dumb dumb.....here it is :)


<?php
//require_once('_header2.php');

if (isset($r_expiration)) {
  set_config('expiration', $r_expiration);
  set_config('num', $r_num);
  save_config();
  redirect('index.php');
  die();
} //if

//$expiration = get_config('expiration');
//$num = get_config('num');

$num = $_POST['num'];
$expiration = $_POST['expiration'];

if($num == "" || $num == 0){    // checks to see if a value entered for num like you asked
header("location : form.php");  // if nothing entered it sends the user back to the form.
}else{
// a number was entered so process the form here
echo "You entered ".$num." for your number and ".$expiration." as the expiration.";
}
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US" xml:lang="en">

<head>
<script type="text/javascript">

function allow_submit()
{
  var f = document.all.frm;
 
  if (f.num.value == "") {
    jAlert("Please enter a number.");
    return false;
  }
  return true;
}

</script>
</head>
<body>
<form name="frm" method="POST" onsubmit="return allow_submit()">
Expiration <input type="text" name="expiration" size="10" value="<?php echo $expiration; ?>">
Num <input type="text" name="num" size="10" value="<?php echo $num; ?>">
    <input type="submit" name="btn_submit" style="color:magenta" value="Save">

</form>
</body>
0
 
wgray05Commented:
I believe you could use the empty function:
if empty($num)
{
   echo "num was empty.";
}

Open in new window


Here is some more info from the PHP site:
http://php.net/manual/en/function.empty.php
0
 
hariboukisCommented:
<?php
require_once('_header2.php');

if (isset($r_expiration)) {
  set_config('expiration', $r_expiration);
  set_config('num', $r_num);
  save_config();
  redirect('index.php');
  die();
} //if

$expiration = get_config('expiration');
$num = get_config('num');

$check = $num * 2; // multiply number by two
$check = $check / 2; // divide number by two
$oktosubmit = "false";
// if $num was a positive number > 0, then $check will equal $num, otherwise it won't
// text will equate to zero and fail this test.  so this verifies that a positive number was entered.
if (($num == $check) and ($num <> 0))
   {
   $message = "You entered a number";
   $status = "true";
   } else {
  $message = "You did not enter a number, or you entered zero";
  }

?>

<head>
</head>

<body>

<?php
if ($status == "true")  // then allow submit
   {
?>
           
<form name=frm method=POST onsubmit="return allow_submit()">
<input type=text name=expiration size=10 value="<?php echo $expiration; ?>">
<input type=text name=num size=10 value="<?php echo $num; ?>">
<input type=submit name=btn_submit value="Save">

<?php
   } else {  // don't allow submit, only print error message
  echo $message;
   } // endif
?>

</form>    
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
wgray05Commented:
Slight modification to the code:
if (empty($num))
{
   echo "num was empty.";
}

Open in new window

0
 
Mark BradyPrincipal Data EngineerCommented:
In your form to accept the posted data just type this.

$num = $_POST['num'];

if($num == "" || $num == 0){    // checks to see if a value entered for num like you asked
header("location : your-form.php");  // if nothing entered it sends the user back to the form.
}else{
// a number was entered so process the form here
}

The above solution is so simple. No javascript validation. All it does is look to see if the num field is empty or = 0 and if it does then it returns back to the form and does nothing. you could take this a step further and send back a flag in the URL to let you know if it was sent back because the num field was empty. To do that, see below:


$num = $_POST['num'];

if($num == "" || $num == 0){    // checks to see if a value entered for num like you asked
header("location : your-form.php?num=0");  // if nothing entered it sends the user back to the form.
}else{
// a number was entered so process the form here
}

Now in the form page, add this code somewhere.

$empty_num = $_GET['num'];
if($empty_num == 0){
// The field was left blank or a zero (0) was typed in.
$error = "You must enter a value in the number field";
}else{
$error = ""; // no error so leave this value blank
}


// now somewhere on your form perhaps next to the "num"  field, add this code.

<?php echo $error; ?>

That's it! If the form is submitted with a blank field, then the error will show on the form and tell the user they need to enter a value into the number field. Change it to suit your form but it's pretty simple.
0
 
lenamtlAuthor Commented:
hariboukis

there is a problem in the code cause
cause I'm got
You did not enter a number, or you entered zero
even if the field has a value in db.

Also the first time the field is empty by default,
with this code
<?php
   } else {  // don't allow submit, only print error message
  echo $message;
   } // endif
?>
 this will never show the form.
0
 
lenamtlAuthor Commented:
elvin66 I like your code better

I have paste this code before the <head>tag is it the good place for this?

$empty_num = $_GET['num'];
if($empty_num == 0){
// The field was left blank or a zero (0) was typed in.
$error = "You must enter a value in the number field";
}else{
$error = ""; // no error so leave this value

I can save the form with empty field
I'm wondering if it's better to use POST instead of GET
in $empty_num = $_GET['num'];

Also I'm having the error message appearing even if a number is in the field

Any clue?
0
 
Mark BradyPrincipal Data EngineerCommented:
No don't place is in the head section it is not javascript. It needs to go in the php script somewhere. Post your form that processes the actual form and I will put the code in for you. Post both the form and the processing php script.
0
 
lenamtlAuthor Commented:
No I didn't pasted the code in the <head>tag  I pasted befrore  the <head>tag  :)

I will retry, I probably made a mistake

0
 
Mark BradyPrincipal Data EngineerCommented:
Ah ok sorry I missread you! Ok try again but please, if you can't get it working, post all your code here (use the file attachment link) and I will do it for you. It only takes about less than a minute to get it running and I'll send it back. Only if you are still stuck with it. Coding should be fun not cause stress :)
0
 
lenamtlAuthor Commented:
here is the code  ( I have removed the table and other css code to keep only the form code)
The form is a one page form.

<?php
require_once('_header2.php');

if (isset($r_expiration)) {
  set_config('expiration', $r_expiration);
  set_config('num', $r_num);
  save_config();
  redirect('index.php');
  die();
} //if

$expiration = get_config('expiration');
$num = get_config('num');
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US" xml:lang="en">

<head>
<script type="text/javascript">

function allow_submit()
{
  var f = document.all.frm;
 
  if (f.num.value == "") {
    jAlert("Please enter a number.");
    return false;
  }
  return true;
}

</script>
</head>
<body>                       
<form name=frm method=POST onsubmit="return allow_submit()">
    <input type=text name=expiration size=10 value="<?php echo $expiration; ?>">
    <input type=text name=num size=10 value="<?php echo $num; ?>">
    <input class="art-button" type=submit name=btn_submit value="Save">
</form>                                
</body> 

Open in new window

     
0
 
Mark BradyPrincipal Data EngineerCommented:
Ok I fixed it up a little. Remember to use quotes around every item when you are setting up forms like name="mark" instead of name=mark. Also, I'm not sure what some of your php code was so I commented it out. Anyway, the form now works and at the moment when you enter values and submit them, they echo what you typed back to the screen. You would of course want to change this to updating the database or something. Hope this helps.
0
 
lenamtlAuthor Commented:
oups ... have you forgot the code ;)
0
 
lenamtlAuthor Commented:
Still not working for me, and it does not save the data in the database with your extra code.

I think this validation should be implement in
this section

if (isset($r_expiration)) {
  set_config('expiration', $r_expiration);
  set_config('num', $r_num);
  save_config();
  redirect('index.php');
  die();
} //if
0
 
lenamtlAuthor Commented:
I realized that this is because it is related to an external function (that does the sqlq('UPDATE ...)
so this is why it is not working properly.

Instead I will not calling this external function and try using
sql('UPDATE config SET ' .     directly

I will get back to you
sorry about this
0
 
lenamtlAuthor Commented:
Thanks
0
 
Mark BradyPrincipal Data EngineerCommented:
My code was just an example of how to write a form and have the results post back to the screen to show you the form was working. In my code I wrote a comment

// a number was entered so process the form here

That means, that is where you put your update database code. Depending on what you are posting in your form is how you would write the update code but using my example form, you would post the following code where I posted that comment.

mysql_query("UPDATE `your table` SET num = '$num', expiration = '$expiration' WHERE id = '$id'")or die(mysql_error());

I added a WHERE clause because you usually need to identify which field to update because if you dont, UPDATE will update ALL records in your table and you don't want that. If you explain what you need to do exactly (giving table names and column names) I can write the proper code for you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.