如何使用PHP验证空值?

时间:2016-12-21 11:40:36

标签: javascript php

我想显示已注册的项目但是如果我使用JS进行验证仍然显示错误,所以我尝试使用PHP进行验证,但仍然无法正常工作。

它将空值插入数据库。

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>

这是php代码:

<?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>";

    }





?>

6 个答案:

答案 0 :(得分:1)

使用||代替&&。这样的事情:这不起作用吗?

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
}

也改变html -

使用mobloc代替mob[]loc[] ...代表名称属性。例如

<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>

还使用mysqli而不是mysql来避免sql injection

答案 1 :(得分:0)

如果我理解您的问题,您希望应用验证以不在数据库中使用null值。您可以使用php empty()函数。

<?php

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

?>

答案 2 :(得分:0)

你可以这样使用

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");
}

由于

答案 3 :(得分:0)

您的Php和Javascript代码是正确的。它适用于我并将所有价值存储在DB中。

我认为你的数据库结构存在问题。请检查一次。有关数据库结构,请参见下图。它对我有用。

enter image description here

答案 4 :(得分:0)

找到正确的答案 PHP代码:

<?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>";

    }





?>

答案 5 :(得分:0)

看起来您的字段包含字段中的空格,默认情况下会使用空值检查数据库列。

如果是这种情况,那么这就解决了。

from("file://downloaded").threads(10).to(...);

希望这会对你有所帮助。