mysql - An example of form validation inside php -


the below show example of implementing form validation inside php detect empty field or unwanted character , alert error message output. have no credit in work, barely compound them suit own site needs. share code did found difficulty find 1 before. answer below provide more advance solution failed make work thou, it's not problem due novice skill in php .

so show basic step novice me before. below code show basic php form validation , email specific email address when user press submit.

<?php    $me =$_server['request_method'];   if ($_post['mail']=='' && $me =="post") { //remember in input tag,set name 'mail' , in form tag set action " ";   $name = preg_replace('/[^a-za-z]/','', $_post['name']);//filter letters $tel = preg_replace('/[^0-9]/','', $_post['tel']);//filter number //$email$regex credit adam khoury www.developphp.com $email = $_post['email']; $regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';   $comments = preg_replace('/[^a-za-z0-9_ %\[\]\.\(\)%&-]/s', '', $_post['comments']); //allow alphanumeric  $error_status = false;//set default error status false  if (empty($email)){ //empty in field, should go through these codes, remember don't put value in input tag thou, or else detect default value $error_email='<h4>please fill in email</h4>'; $error_status = true; //error status toggle } else if (preg_match($regex, $email)) { //if ensure format of email correctly entered    } else {       $error_email='<h4>this invalid email. please try again.</h4>';      $error_status = true; }    if (empty($name)){ $error_name= '<h4>please fill name</h4>'; $error_status = true; }   if (empty($tel)){ $error_tel ='<h4>please fill contact number</h4>'; $error_status = true; }  if (empty($comments)){ $error_comments ='<h4>please give comments</h4>'; $error_status = true; }   if(!$error_status) { $success='<h4>thanks comments. reply shortly</h4>'; $to_address="someone@gmail.com"; $subject="online comments";  $message="input online comments box.\n\n"; $message .="name: ".$name."\n"; $message .="tel: ".$tel."\n"; $message .="email: ".$email."\n"; $message .="comments: ".$comments."\n";  mail($to_address, $subject, $message); unset($name,$tel,$email,$comments); } }  ?> 

you problem in if statement

replace this:

if (empty($_post['customer_name']) $err[] = "username field required";   if (empty($_post['tel_num']) $err[] = "comments field required";   

with:

if (empty($_post['customer_name'])) {   $err[] = "username field required";   }   if (empty($_post['tel_num'])) {   $err[] = "comments field required";   } 

the problem missed ) after ) standing.

so had this:

empty($_post['customer_name']) //notice 1 ( 

but have this:

empty($_post['customer_name'])) //notice 2 ( 

also use shorttag (<?) opening php better use <?php in other scripts

edit

in cart.php should use code:

<?php   if ($_server['request_method']=='post') {     $err = array();   //performing validations , raising corresponding errors   if (empty($_post['customer_name'])) {   $err[] = "username field required";   }     if (empty($_post['tel_num'])) {   $err[] = "comments field required";     }    if (empty($err)) {       //if no errors - saving data , redirect     header("location: ".$_server['php_self']);     exit;   }  else {     // field values should escaped according html standard     foreach ($_post $key => $val) {       $form[$key] = htmlspecialchars($val);     }   } } else {   $form['customer_name'] = 'm;   $form['tel_num'] = '';   } include 'form.tpl.php'; ?>   

edit2 checked again code in question. not find problems. did make little changes

i think when use script should working:

<?php     session_start();     /* created adam khoury @ www.developphp.com */      error_reporting(e_all);     ini_set('display_errors', '1');     // connect mysql database       include "storescripts/connect_to_mysqli.php";      // determine page id use in our query below ---------------------------------------------------------------------------------------     if (!empty($_get['pid'])) {         $pageid = 1;     } else {         $pageid = preg_replace("[^0-9]", "", $_get['pid']); // filter numbers security     }      // query body section proper page     $sqlcommand = "select pagebody pages id='$pageid' limit 1";     $query = mysqli_query($myconnection, $sqlcommand) or die(mysqli_error());     while ($row = mysqli_fetch_array($query)) {         $body = $row["pagebody"];     }     mysqli_free_result($query);     //---------------------------------------------------------------------------------------------------------------------------------------------------------------     // query module data display ---------------------------------------------------------------------------------------------------------------     $sqlcommand = "select modulebody modules showing='1' , name='footer' limit 1";     $query = mysqli_query($myconnection, $sqlcommand) or die(mysqli_error());     while ($row = mysqli_fetch_array($query)) {         $footer = $row["modulebody"];     }     mysqli_free_result($query);     //---------------------------------------------------------------------------------------------------------------------------------------------------------------     // query module data display ---------------------------------------------------------------------------------------------------------------     $sqlcommand = "select modulebody modules showing='1' , name='custom1' limit 1";     $query = mysqli_query($myconnection, $sqlcommand) or die(mysqli_error());     while ($row = mysqli_fetch_array($query)) {         $custom1 = $row["modulebody"];     }     mysqli_free_result($query);     //---------------------------------------------------------------------------------------------------------------------------------------------------------------     // build main navigation menu , gather page data here -----------------------------------------------------------------------------       $sqlcommand = "select id, linklabel pages showing='1' order id desc";     $query = mysqli_query($myconnection, $sqlcommand) or die(mysqli_error());      $menudisplay = '';     while ($row = mysqli_fetch_array($query)) {         $pid = $row["id"];         $linklabel = $row["linklabel"];         $menudisplay .= '<a href="index.php?pid=' . $pid . '">' .                 $linklabel . '</a><br />';     }     mysqli_free_result($query);     //---------------------------------------------------------------------------------------------------------------------------------------------------------------     //mysqli_close($myconnection);      // file www.developphp.com curriculum material     // written adam khoury january 01, 2011     // http://www.youtube.com/view_play_list?p=442e340a42191003     // script error reporting     /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     //       section 1 (if user attempts add cart product page)     /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     if (isset($_post['pid'])) {         $pid = $_post['pid'];         $wasfound = false;         $i = 0;         // if cart session variable not set or cart array empty         if (!isset($_session["cart_array"]) || count($_session["cart_array"]) < 1) {             // run if cart empty or not set             $_session["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1));         } else {             // run if cart has @ least 1 item in             foreach ($_session["cart_array"] $each_item) {                 $i++;                 while (list($key, $value) = each($each_item)) {                     if ($key == "item_id" && $value == $pid) {                         // item in cart let's adjust quantity using array_splice()                         array_splice($_session["cart_array"], $i - 1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));                         $wasfound = true;                     } // close if condition                 } // close while loop             } // close foreach loop             if ($wasfound == false) {                 array_push($_session["cart_array"], array("item_id" => $pid, "quantity" => 1));             }         }         header("location: cart.php");         exit();     }      /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     //       section 2 (if user chooses empty shopping cart)     /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     if (isset($_get['cmd']) && $_get['cmd'] === 'emptycart') {         unset($_session["cart_array"]);     }      /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     //       section 3 (if user chooses adjust item quantity)     /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     if (isset($_post['item_to_adjust']) && $_post['item_to_adjust'] != "") {         // execute code         $item_to_adjust = $_post['item_to_adjust'];         $quantity = $_post['quantity'];         $quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter numbers         if ($quantity >= 100) {             $quantity = 99;         }         if ($quantity < 1) {             $quantity = 1;         }         if (empty($quantity)) {             $quantity = 1;         }         $i = 0;         foreach ($_session["cart_array"] $each_item) {             $i++;             while (list($key, $value) = each($each_item)) {                 if ($key == "item_id" && $value == $item_to_adjust) {                     // item in cart let's adjust quantity using array_splice()                     array_splice($_session["cart_array"], $i - 1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));                 } // close if condition             } // close while loop         } // close foreach loop     }      /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     //       section 4 (if user wants remove item cart)     /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     if (isset($_post['index_to_remove']) && $_post['index_to_remove'] !== '') {         // access array , run code remove array index         $key_to_remove = $_post['index_to_remove'];         if (count($_session["cart_array"]) <= 1) {             unset($_session["cart_array"]);         } else {             unset($_session["cart_array"][$key_to_remove]);             sort($_session["cart_array"]);         }     }      /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     //       section 5  (render cart user view on page)     /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////     $cartoutput = "";     $carttotal = "";     $pp_checkout_btn = '';     $product_id_array = '';      if (!isset($_session["cart_array"]) || count($_session["cart_array"]) < 1) {         $cartoutput = "<h3 align='center'>your shopping cart empty</h3>";     } else {         // start paypal checkout button          $pp_checkout_btn .= '<form action="http://chenlikpharmacy.freeserver.me/order_list.php" method="post">     <input type="hidden" name="cartoutput" value = "$cartoutput">';          // start each loop         $i = 0;         foreach ($_session["cart_array"] $each_item) {             $item_id = $each_item['item_id'];             $sqlcommand = "select * products id='$item_id' limit 1";             $sql = mysqli_query($myconnection, $sqlcommand);             while ($row = mysqli_fetch_array($sql)) {                 $product_name = $row["product_name"];                 $price = $row["price"];                 $details = $row["details"];             }             $pricetotal = $price * $each_item['quantity'];             $carttotal = $pricetotal + $carttotal;             setlocale(lc_monetary, "en_us");             $pricetotal = money_format("%10.2n", $pricetotal);     // dynamic checkout btn assembly              $pp_checkout_btn .= '<input type="hidden" name="item_name[]" value="' . $product_name . '">     <input type="hidden" name="amount[]" value="' . $price . '">     <input type="hidden" name="quantity[]" value="' . $each_item['quantity'] . '">  ';             // create product array variable             $product_id_array .= "$item_id-" . $each_item['quantity'] . ",";             // dynamic table row assembly             $cartoutput .= "<tr>";             $cartoutput .= '<td><a href="product.php?id=' . $item_id . '">' . $product_name . '</a><br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name . '" width="40" height="52" border="1" /></td>';             $cartoutput .= '<td>' . $details . '</td>';             $cartoutput .= '<td>rm' . $price . '</td>';             $cartoutput .= '<td><form action="cart.php" method="post">             <input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" />             <input name="adjustbtn' . $item_id . '" type="submit" value="change" />             <input name="item_to_adjust" type="hidden" value="' . $item_id . '" />             </form></td>';             //$cartoutput .= '<td>' . $each_item['quantity'] . '</td>';             $cartoutput .= '<td>' . $pricetotal . '</td>';             $cartoutput .= '<td><form action="cart.php" method="post"><input name="deletebtn' . $item_id . '" type="submit" value="x" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>';             $cartoutput .= '</tr>';             $i++;         }         setlocale(lc_monetary, "ms_my");         $carttotal = money_format("%10.2n", $carttotal);         $carttotal = "<div style='font-size:18px; margin-top:12px;' align='right'>cart total : " . $carttotal . " myr</div>";         // finish paypal checkout btn         $pp_checkout_btn .= '<input type="hidden" name="custom" value="' . $product_id_array . '">     name: <input type="text" name="customer_name">     <br/>     tel: <input type="text" name="tel_num">          <input type="submit" value="submit">         </form>';     }      if ($_server['request_method'] == 'post') {         $err = array();         //performing validations , raising corresponding errors         if (empty($_post['customer_name'])) {             $err[] = "username field required";         }         if (empty($_post['tel_num'])) {             $err[] = "comments field required";         }          if (empty($err)) {             //if no errors - saving data , redirect             header("location: " . $_server['php_self']);             exit;         } else {             // field values should escaped according html standard             foreach ($_post $key => $val) {                 $form[$key] = htmlspecialchars($val);             }         }     } else {         $form['customer_name'] = '';         $form['tel_num'] = '';     }     include 'form.tpl.php';     ?>       <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">     <html lang="en-us" xmlns="http://www.w3.org/1999/xhtml" dir="ltr">         <head>             <title>chenlik pharmacy online catalogue</title>             <meta http-equiv="content-type" content="text/html; charset=utf-8" />             <link rel="shortcut icon" href="css/images/favicon.ico" />             <link rel="stylesheet" href="css/style.css" type="text/css" media="all" />             <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>             <script type="text/javascript" src="js/jquery.jcarousel.min.js"></script>             <!--[if ie 6]>             <script type="text/javascript" src="js/png-fix.js"></script>             <![endif]-->             <script type="text/javascript" src="js/functions.js"></script>         </head>         <body>             <!-- header -->             <div id="header" class="shell">                 <div id="logo">                     <h1><a href="http://chenlikpharmacy.freeserver.me/index.php">chenlik pharmacy sdn. bhd.</a></h1><span><a href="http://chenlikpharmacy.freeserver.me">serve care & passion</a></span></div>                  <!-- navigation -->                 <div id="navigation">                     <ul>                         <li><a href="http://chenlikpharmacy.freeserver.me/index.php" >home</a></li>                         <li><a href="http://chenlikpharmacy.freeserver.me/product_list.php">products</a></li>                         <li><a href="http://chenlikpharmacy.freeserver.me/promotions.php">promotions</a></li>                         <li><a href="http://chenlikpharmacy.freeserver.me/profile.php">profile</a></li>                         <li><a href="http://chenlikpharmacy.freeserver.me/about_us.php" class="active">about us</a></li>                         <li><a href="http://chenlikpharmacy.freeserver.me/contacts.php" >contacts</a></li>                     </ul>                 </div>                  <!-- end navigation -->                  <div class="cl">&nbsp;</div>                  <!-- login-details -->                  <div id="login-details">                      <p>welcome, <a href="#" id="user">guest</a> .</p>                     <p><a href="http://chenlikpharmacy.freeserver.me/cart.php" class="cart" ><img src="css/images/cart-icon.png" alt="" /></a>shopping cart <a href="http://chenlikpharmacy.freeserver.me/cart.php" class="sum"> cart total</a></p>                  </div>                  <!-- end login-details -->              </div>             <!-- end header -->               <!-- main -->              <div id="main" class="shell">                   <!-- products -->                 <div id="main" class="products">                                 <table width="100%" border="1" cellspacing="0" cellpadding="6">                         <tr>                             <td width="18%" bgcolor="#c5dffa"><strong>product</strong></td>                             <td width="45%" bgcolor="#c5dffa"><strong>product description</strong></td>                             <td width="10%" bgcolor="#c5dffa"><strong>unit price</strong></td>                             <td width="9%" bgcolor="#c5dffa"><strong>quantity</strong></td>                             <td width="9%" bgcolor="#c5dffa"><strong>total</strong></td>                             <td width="9%" bgcolor="#c5dffa"><strong>remove</strong></td>                         </tr>     <?php echo $cartoutput; ?><br/>          <!-- <tr>             <td>&nbsp;</td>             <td>&nbsp;</td>             <td>&nbsp;</td>             <td>&nbsp;</td>             <td>&nbsp;</td>             <td>&nbsp;</td>         </tr> -->                     </table>     <?php echo $carttotal; ?>                     <br />                     <br />     <?php echo $pp_checkout_btn; ?>                     <br />                     <br />                     <a href="cart.php?cmd=emptycart">click here empty shopping cart</a>                      <!-- end products -->                       <div class="cl">&nbsp;</div>                  </div>                    <div class="cl">&nbsp;</div>              </div>              <!-- end main -->              <!-- footer -->              <div id="footer" class="shell">                  <div class="top">                      <div class="cnt">                          <div class="col about">                              <h4>about chenlik pharmacy sdn. bhd.</h4>      <?php echo $custom1; ?>                          </div>                          <div class="col store">                              <h4>store</h4>      <?php echo $footer; ?>                          </div>                          <div class="col" id="newsletter">                              <h4>newsletter</h4>                              <p>this function not activate yet. </p>                              <form action="" method="post">                                  <input type="text" class="field" value="your name" title="your name" />                                  <input type="text" class="field" value="email" title="email" />                                  <div class="form-buttons"><input type="submit" value="submit" class="submit-btn" />                                 </div>                              </form>                          </div>                          <div class="cl">&nbsp;</div>                          <div class="copy">                              <p>&copy;2013 <a href="http://chenlikpharmacy.freeserver.me">chenlik pharmacy sdn. bhd.</a>&nbspdesign <a href="http://css-free-templates.com/">css-free-templates.com</a> &nbsp.source code credit to: <a href="http://www.developphp.com">adam khoury</a>. modified & complied by: philip tiong</p>                         </div>                     </div>                 </div>             </div>             <!-- end footer -->         </body>     </html> 

to show errors need add in html want display errors:

<?php if (!empty($err)) : foreach ($err $error) : echo $error;  endforeach; endif; 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -