Solved

Server side validation for PHP form

Posted on 2011-03-18
17
552 Views
Last Modified: 2012-05-11
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
0
Comment
Question by:lenamtl
  • 8
  • 6
  • 2
  • +1
17 Comments
 
LVL 3

Expert Comment

by:wgray05
ID: 35168240
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
 

Expert Comment

by:hariboukis
ID: 35168241
<?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
 
LVL 3

Expert Comment

by:wgray05
ID: 35168244
Slight modification to the code:
if (empty($num))
{
   echo "num was empty.";
}

Open in new window

0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 35168441
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
 
LVL 24

Author Comment

by:lenamtl
ID: 35168550
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
 
LVL 24

Author Comment

by:lenamtl
ID: 35168628
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
 
LVL 20

Expert Comment

by:Mark Brady
ID: 35169377
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
 
LVL 24

Author Comment

by:lenamtl
ID: 35169660
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 20

Expert Comment

by:Mark Brady
ID: 35170415
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
 
LVL 24

Author Comment

by:lenamtl
ID: 35172357
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
 
LVL 20

Expert Comment

by:Mark Brady
ID: 35173024
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
 
LVL 24

Author Comment

by:lenamtl
ID: 35173404
oups ... have you forgot the code ;)
0
 
LVL 20

Accepted Solution

by:
Mark Brady earned 500 total points
ID: 35173569
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
 
LVL 24

Author Comment

by:lenamtl
ID: 35173705
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
 
LVL 24

Author Comment

by:lenamtl
ID: 35173844
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
 
LVL 24

Author Closing Comment

by:lenamtl
ID: 35173866
Thanks
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 35174833
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

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now