savagenoob Posted February 23, 2009 Share Posted February 23, 2009 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 More sharing options...
JonnoTheDev Posted February 23, 2009 Share Posted February 23, 2009 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); } Link to comment https://forums.phpfreaks.com/topic/146541-form-validation-using-php/#findComment-769331 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.