mysql - Validating user input using php -


i'm new php , mysql , i'm trying check if user has entered a coupls of textboxes , check if has been entered string. want check before posting database. want html form retain value entered user. please how achieve this.

here's i've done far. works still shows data has been entered successfully.

if(isset($_post['register'])){   //php field validations if($_post['fname']==""){     echo "first name required <br/>";  } else{    $fname= filter_var($_post['fname'], filter_sanitize_string); } if($_post['lname']==""){     echo "last name required <br/>"; } else{     $lname= $_post['lname']; } if($_post['email']==""){     echo "email address required <br/>"; } else{      $email= $_post['email']; } if($_post['pword']==""){     echo "password required<br/>"; } else{       $pword= $_post['pword']; }    $fname=mysql_real_escape_string($fname); $lname=mysql_real_escape_string($lname); $email=mysql_real_escape_string($email); $pword=mysql_real_escape_string($pword);  require_once 'scripts/connect_to_mysql.php'; $sql = "insert customer ".        "(first_name,last_name, email, password, date_added) ".        "values('$fname','$lname','$email','$pword', now())";        //echo $sql; mysql_select_db('online_store'); $result = mysql_query( $sql, $conn ); if(! $result )  {   die('could not enter data: ' . mysql_error()); } echo "<span style='color:green;'>entered data successfully</span>"; mysql_close($conn); } ?> 

firstly , importantly, should change mysql either mysqli or pdo.

secondly, ensure fields entered before submitting, loop through inputs, checking each if empty, , running input specific checks wish. i.e checking if input string can is_string($variable).

if of checks fail, set variable e.g. $failedvalidation, wrap sql execution code in if statement - if $failedvalidation !isset, or set false, want handle - run code.

instead of using $fname=mysql_real_escape_string($fname); use $fname = htmlspecialchars($fname);.

looping through $_post array:

$validated = true; // validated needs set true, sql code run  // loop through variables stored in $_post array foreach($_post $value)  {     if(empty($value))  // if of $_post variables empty, set $validated false     {        $validated = false;     } }  // if none of fields empty, $validated have remained true after our loop if($validated == true) {    // run sql code } 

hopefully i've explained in way can understand, , hope helps you.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -