Jump to content

[SOLVED] Check for require fields, any suggestion to my coding?


ubuntu

Recommended Posts

Dear eveyone,

 

I'm developing an online reservation system. The code below (dummy code) is to check for required fields (every fields are mandatory enter by client).

 

if (!$_POST['fullname'] || !$_POST['ic_no'] || !$_POST['gender'] || !$_POST['address'] || !$_POST['city'] || !$_POST['state'] || !$_POST['contact_no'] || !$_POST['hp_no'] || !$_POST['email'] || !$_POST['username'] || !$_POST['password'] || !$_POST['confirmpassword']) {
     die("You didn't enter mandatory field. Click <a href=\"./register.php\">Here</a> to reenter your information.");
}

 

I'm a beginner in PHP and not good in programming, hope you can help me to produce a better coding. Any advice or suggestion are most welcome. Thank you for your kind attention. Regards.

I would suggest seperating them out. Something like this:

 

<?php
$error = NULL;

if (!isset($_POST['fullname'])) {
     $error .= "Full name is required.<br />";
}
if (!isset($_POST['ic_no'])) {
     $error .= "IC_NO is required.<br />";
}
if (!isset($_POST['gender'])) {
     $error .= "Gender is required.<br />";
}

if (!is_null($error)) {
    die($error);
}

// process here
?>

 

This way you can tell your user exactly what is wrong. There is probably a better way to set it up than what I have, but yea it works.

What are you wanting to do differently?

 

For one, I would suggest not using "die" and instead building a proper error page. In fact, I would repopulate the form with any values the user did enter.

 

Hre is an example - not a full script:

 

<?php




if (isset($_POST[])) { //User posted the page

 $error = false;

 //Check the req. fields
 if (!$_POST['fullname'] || !$_POST['ic_no'] || !$_POST['gender']
      || !$_POST['address'] || !$_POST['city'] || !$_POST['state']
      || !$_POST['contact_no'] || !$_POST['hp_no'] || !$_POST['email']
      || !$_POST['username'] || !$_POST['password'] || !$_POST['confirmpassword']) {
   $error = "You didn't enter all mandatory fields.";
 }

 if (!$error) {

   //Process the form data

 }

}

?>

<html>
<head></head>
<bodY>
FORM TITLE
<br><br>
<?php if ($error) { echo $error; } ?>
<br><br>
Full Name: <input type="text" name="fullname" value="<?=$_POST['fullname']>?"><br>
IC Number: <input type="text" name="ic_no" value="<?=$_POST['ic_no']>?"><br>
Gender: <input type="radio" name="gender" value="male" <?=(($_POST['gender']=='male')?'checked':'')> Male
       <input type="radio" name="gender" value="female" <?=(($_POST['gender']=='female')?'checked':'')> Female<br>
Address: <input type="text" name="address" value="<?=$_POST['address']>?"><br>

</body>
</html>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.