1

I want to display registered item but if I doing validation using JS still it showing error so I have tried validation using PHP but still it's not working.

It's inserting null value to database.

HTML CODE:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>location</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="validator.js"

  <script>

  </script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC1Eg-TCCD6bFLPx9rHqwMF4KblGr-Wfbg&libraries=places"></script>
<script type="text/javascript">
 function isNumberKey(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    var regex = /[0-9]/;
    if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) theEvent.preventDefault();
    }
}
</script>

<script>
$(document).ready(function(){

    //$("#submit").click(function(){
    $("#form").on('submit',(function(e) {
        e.preventDefault(); // Prevent Default Submission
        //console.log(new FormData(this));//return false;
        $.ajax({
            url: "location.php",
            type: "POST",
            data: new FormData(this),
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData:false, 
            success: function(result){

                $("#result").html(result);
            }
        });

         $(".email").each(function() {
         var email = $(this).val();

if (isEmail(email)) {
alert('Nice!! your Email is valid, now you can continue..');
}
else {
alert('Invalid Email Address');
e.preventDefault();
}
        });

        $(".mob").each(function() {
         var mob = $(this).val();
          console.log(mob);
if (validation(mob)) {
alert('Nice!! your Mobile is valid, now you can continue..');

}
else{
alert('Invalid mobile');

e.preventDefault();

}
        });




    }));

});

/*
function validForm(){

  //var validation = true;
  if(isEmail() && validation())
  {
    return true;
  }
  else
  {
    return false;
  }
}
*/


function isEmail(email) {

var regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;

  var res = regex.test(email);

  if (res==false ){


  return false;
  }
  else {
  return true;
  }


}


var nextRowID = 1;
var id=1;
function validation(mob)  
{  



  if(mob.length!=10)
  { 

  return false;
  }
  else{
  return true;
  }

}





 function addFields(){

            var container = document.getElementById("container");


             var id = ++nextRowID;
                container.appendChild(document.createTextNode("Name:"));
                var inputname = document.createElement("input");
                inputname.type = "text";
                inputname.id= id+'_name';
                inputname.name= "name[]";
                inputname.required =true;
                inputname.className= "form-control";
                container.appendChild(inputname);

                container.appendChild(document.createTextNode("location"));
                var select= document.createElement("select");
                select.name= "loc[]";
                select.className= "form-control";
                select.required =true;

                var option0= document.createElement("option");
                option0.text = "select location";
                option0.value = "";
                select.appendChild(option0);

                var option1= document.createElement("option");
                option1.text = "mumbai";
                option1.value = "mumbai";
                select.appendChild(option1);

                var option2= document.createElement("option");
                option2.text = "delhi";
                option2.value = "delhi";
                select.appendChild(option2);

                var option3= document.createElement("option");
                option3.text = "chennai";
                option3.value = "mumbai";
                select.appendChild(option3);

                var option4= document.createElement("option");
                option4.text = "himmatnagar";
                option4.value = "himmatnagar";
                select.appendChild(option4);

                container.appendChild(select);





                container.appendChild(document.createTextNode("mobile"));
                var input_m = document.createElement("input");
                input_m.type = "text";
                input_m.id= id+'_mobile';
                input_m.name= "mob[]";
                //input_m.onkeypress="return isNumberKey(event)";
                input_m.setAttribute('onkeypress', 'return isNumberKey(event)');

                input_m.className="mob form-control";
                input_m.required =true;
                container.appendChild(input_m);


                container.appendChild(document.createTextNode("email"));
                var input_e = document.createElement("input");
                input_e.type = "email";
                input_e.id= id+'_email';
                input_e.name= "email[]";
                input_e.required =true;
                input_e.className="email form-control";
                //input_e.setAttribute('onblur', 'return isEmail(email)');
                container.appendChild(input_e);

                container.appendChild(document.createElement("br"));
                container.appendChild(document.createElement("br"));

        }
</script>


</head>
<body>

<div class="container-fluid">
<div class="page-header">
  <h2>Location</h2>
  </div>
  <div class="form-group">
  <!--<form class="form" name="form" id="form" role="form"  method="post">-->
  <form id="form"  data-toggle="validator" action="" role="form" method="post" enctype="multipart/form-data" onsubmit="return valid();" >



 <div class="form-group has-feedback">

        <label for="inputName" class="control-label">Name</label>
      <input type="text" class="name form-control" id="name"  name="name[]" placeholder="Enter name" required>
    <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
    </div>
    <label for="inputEmail" class="control-label">Location</label>
     <select class="form-control" name="loc[]" id="select" required>
     <option value="">select location</option>
    <option value="Mumbai">Mumbai</option>
    <option value="Delhi">Delhi</option>
    <option value="Chennai">Chennai</option>
    <option value="Himmatnagar">Himmatnagar</option>
     <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
</select>


     <div class="form-group has-feedback">
      <label for="inputEmail" class="control-label">Mobile</label>
     <input type="text" class="mob form-control" id="mob" name="mob[]" onkeypress="return isNumberKey(event)"
   placeholder="Enter mobile no" class="onlyno" required>
   <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
   </div>

        <div class="form-group has-feedback">
      <label for="inputEmail" class="control-label">Email</label>
      <input type="email" id="inputEmail" class="email form-control" name="email[]" placeholder="Enter email" data-error="Email address is invalid" required>
      <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
     <div class="help-block with-errors"></div>
</div>
        <input type="button" class="btn btn-default" id="newAutocomplete" onclick="addFields();" value="add" />

      <br><br>
 <div id="container" >
 </div>


    <input class="btn btn-primary" type="submit"  /><br><br>
    </form>

    </div>
    <div id="result"></div>

    <br><br>

</div>

</body>
</html>

And here is php code:

<?php   




    //var_dump($_REQUEST);die;
    $con = mysql_connect("localhost","root","");
    if (!$con){
    die("Can not connect: " . mysql_error());
    }
    mysql_select_db("sll",$con);
    //print_r($_POST['name']);
    var_dump(($_POST['name']=="" || $_POST['name']==null) && ($_POST['loc']=="" || $_POST['loc']==null) && ($_POST['mob']=="" || $_POST['mob']==null) && ($_POST['email']=="" || $_POST['email']==null));die;
    if($_POST['name']=="" && $_POST['loc']=="" && $_POST['mob']=="" && $_POST['email']=="")
    {
    echo "pls enter all fleid ";
    exit;
    }
    else{

     echo "<table border='1'>
  <tr><th>name</th>
  <th>location</th>
  <th>mobile</th>
  <th>email</th></tr>";

    if(isset($_POST['name']))
    {   $name=$_POST['name'];}
    if(isset($_POST['loc']))
    {$loc=$_POST['loc'];}
    if(isset($_POST['mob']))
    {   $mob=$_POST['mob'];}
    if(isset($_POST['email']))
    {$email=$_POST['email'];}

    //var_dump($name);die;
//please assume boxes = training
    foreach($name as $key => $row){  

    $nameSav = $name[$key];
    $locSav = $loc[$key];
    $mobSav = $mob[$key];
    $emailSav = $email[$key];

      echo "<tr>";
      echo "<td>" .$nameSav."</td>";
      echo "<td>" .$locSav."</td>";
      echo "<td>" .$mobSav."</td>";
      echo "<td>" .$emailSav."</td>";
      echo"</tr>";


        $AddQuery ="INSERT INTO db1 (name,loc,mob,email) VALUES ('$nameSav','$locSav','$mobSav','$emailSav')";
       $result= mysql_query($AddQuery, $con);
       $result1= mysql_query ("select * from db1");
    }

    if ($result){
    echo "Registered Successfully"; 

    }

else{
    echo "Not registered";

}
    while($row = mysql_fetch_array($result1))
    {
       echo "<tr>";
      echo "<td>" .$row['name']."</td>";
      echo "<td>" .$row['loc']."</td>";
      echo "<td>" .$row['mob']."</td>";
      echo "<td>" .$row['email']."</td>";
      echo"</tr>";
    }
echo"</table>";

    }





?>
4
  • is_null() will help you Commented Dec 21, 2016 at 11:42
  • im getting null value from form Commented Dec 21, 2016 at 11:43
  • Check empty() php.net/manual/en/function.empty.php and change && to || in the if statement Commented Dec 21, 2016 at 11:43
  • its not working Commented Dec 21, 2016 at 11:44

6 Answers 6

1

Use || instead of &&. Something like: Is this not working ?

if(empty($_POST['name']) || empty($_POST['loc']) || 
   empty($_POST['mob']) || empty($_POST['email'])) {
  echo "pls enter all fleid ";
  exit;
}
else {
  //your remaining code to insert
}

Change the html too -

Use mob, loc instead of mob[], loc[]... for name attribute. Eg

<input type="email" id="inputEmail" class="email form-control" name="email" <-- use email not email[]
placeholder="Enter email" data-error="Email address is invalid" required>

Also use mysqli instead of mysql to avoid sql injection.

Sign up to request clarification or add additional context in comments.

2 Comments

its not working its takes one value in name because it is array it some some value
Check the update, dont use array in name attribute for simple text html
0

Seems your field containing the spaces in field and your database column is checked with null value by default.

So here is solution if this is the case.

if($_POST['name'] == ' ' || $_POST['loc'] == ' ' || $_POST['mob'] == ' ' ||     $_POST['email'] == ' ') {
     print 'Please input value for the blank field';
     exit;
}
else {
   // do the insertion in database
}

Hope this will help you.

Comments

0

correct answer found PHP Code:

<?php   




    //var_dump($_REQUEST);die;
    $con = mysql_connect("localhost","root","");
    if (!$con){
    die("Can not connect: " . mysql_error());
    }
    mysql_select_db("sll",$con);



     echo "<table border='1'>
  <tr><th>name</th>
  <th>location</th>
  <th>mobile</th>
  <th>email</th></tr>";

    if(isset($_POST['name']))
    {   $name=$_POST['name'];}
    if(isset($_POST['loc']))
    {$loc=$_POST['loc'];}
    if(isset($_POST['mob']))
    {   $mob=$_POST['mob'];}
    if(isset($_POST['email']))
    {$email=$_POST['email'];}

    //var_dump($name);die;
//please assume boxes = training
    foreach($name as $key => $row){  

    $nameSav = $name[$key];
    $locSav = $loc[$key];
    $mobSav = $mob[$key];
    $emailSav = $email[$key];


        if($nameSav=="" && $locSav=="" && $mobSav=="" && $emailSav=="")
    {
    echo "pls enter all fleid ";
    exit;
    }
    else{

        $AddQuery ="INSERT INTO db1 (name,loc,mob,email) VALUES ('$nameSav','$locSav','$mobSav','$emailSav')";
       $result= mysql_query($AddQuery, $con);
       $result1= mysql_query ("select * from db1");
    }
    }
    if ($result){
    echo "Registered Successfully"; 

    }

else{
    echo "Not registered";

}
    while($row = mysql_fetch_array($result1))
    {
       echo "<tr>";
      echo "<td>" .$row['name']."</td>";
      echo "<td>" .$row['loc']."</td>";
      echo "<td>" .$row['mob']."</td>";
      echo "<td>" .$row['email']."</td>";
      echo"</tr>";
    }
echo"</table>";

    }





?>

1 Comment

This looks like it has SQL injection vulnerabilities. To fix it, consider looking into parameter binding. You will need to update your database library to either MySQLi or PDO.
0

Your Php and Javascript code is correct. it's working for me and store all value in DB.

I think problems in your DB structure. Please check it once. Please see below image for DB structure. it's working for me.

enter image description here

Comments

0

You can use like this

function check_post( $arr ) {
     foreach( $arr as $value ) {
          if( $value =='' ) return false;
      }
     return true;
 }

$check = check_post( $_POST );
if($check == false){
   die("Please enter all values");
}

Thanks

1 Comment

Please use the edit link explain how this code works and don't just give the code, as an explanation is more likely to help future readers. See also How to Answer.
0

If I understand your question, you want to apply a validation to not let null values in the database. You can use the php empty() function.

<?php

if(empty($_POST['name'])) {
    die("Please enter with the name!");
}

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.