Jump to content

Form Validation using PHP


savagenoob

Recommended Posts

I was wondering the simplest way to do form field validation using PHP. I have forms setup and most the time post to itself, then use either switch or if(isset) to identify which form was submitted on the page. I basically just need to validate that the variables are not empty. I know there is empty(), but cant figure a logical way to use it. Here's some code sample...

<?php
if (isset($_POST['deluser'])) {
    $agency = $_SESSION['SESS_AGENCY'];
    $member_id = mysql_escape_string($_POST['member_id']);
    $sql = mysql_query("DELETE FROM members WHERE member_id = '$member_id' AND agency = '$agency'");
    mysql_free_result($sql);
    echo mysql_error();
    echo "<b>User Deleted Successfully!<br>";
    echo "<meta http-equiv=Refresh content=2;url=admin.php>";
} elseif (isset($_POST['adduser'])) {
    $firstname = mysql_escape_string($_POST['firstname']);
    $lastname = mysql_escape_string($_POST['lastname']);
    $empid = mysql_escape_string($_POST['empid']);
    $username = mysql_escape_string($_POST['username']);
    $password = mysql_escape_string(md5($_POST['password']));
    $office = mysql_escape_string($_POST['office']);
    $agency = $_SESSION['SESS_AGENCY'];

    $usql = mysql_query("INSERT INTO members SET firstname = '$firstname', lastname = '$lastname', empid = '$empid', login = '$username', passwd = '$password', office = '$office', agency = '$agency'");
    mysql_free_result($usql);
    echo mysql_error();
    echo "<b>User Added Successfully!<br>";
    echo "<meta http-equiv=Refresh content=2;url=admin.php>";
?>

 

Link to comment
https://forums.phpfreaks.com/topic/146541-form-validation-using-php/
Share on other sites

Along the lines of

 

$errors = array();
if(!strlen(trim($_POST['name']))) {
  $errors[] = "Name";
}
if(!strlen(trim($_POST['address']))) {
  $errors[] = "Address";
}

if(!count($errors)) {
  // no errors - insert record
  foreach($_POST as $key => $val) {
    $_POST[$key] = mysql_real_escape_string(trim($_POST[$key]));
  }
  mysql_query("INSERT INTO table SET name='".$_POST['name']."',address='".$_POST['address']."'");
  header("Location:xyz.php");
  exit();
}
else {
   // display errors
   echo "You need to complete the following fields: ".implode(", ", $errors);
}

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.