值在不输入数据的情况下插入到数据库中


Values get inserted in database without entering data

我正在尝试用php格式联系表单,其中的详细信息存储在数据库中。如果我不输入任何值,它会显示错误消息,但它会存储在数据库中。当错误消息显示不应在数据库中输入数据时,如何验证表单。这是代码

<?php
 $username = "root";
$password = "";
$hostname = "localhost"; 
$db = "abc";
//connection to the database
$name="";
$email="";
$batch="";
$mobile="";
    if (isset($_POST['submit'])) {
    $error = "";
    if (!empty($_POST['name'])) {
    $name = $_POST['name'];
    } else {
    $error .= "You didn't type in your name. <br />";
    }
    if (!empty($_POST['email'])) {
    $email = $_POST['email'];
      if (!preg_match("/^[_a-z0-9]+('.[_a-z0-9-]+)*@[a-z0-9-]+('.[a-z0-9-]+)*('.[a-z]{2,3})$/i", $email)){ 
      $error .= "The e-mail address you entered is not valid. <br/>";
      }
    } else {
    $error .= "You didn't type in an e-mail address. <br />";
    }
if (!empty($_POST['batch'])) {
    $batch = $_POST['batch'];
    } else {
    $error .= "You didn't type batch. <br />";
    }
     if(($_POST['code']) == $_SESSION['code']) { 
    $code = $_POST['code'];
    } else { 
    $error .= "The captcha code you entered does not match. Please try again. <br />";    
    }

    if (!empty($_POST['mobile'])) {
    $mobile = $_POST['mobile'];
    } else {
    $error .= "You didn't type your Mobile Number. <br />";
    }



    if (empty($error)) {


 $success = "<b>Thank you! Your message has been sent!</b>";

    }
    }
    ?>
              <div id="contactForm">

                <?php
      if (!empty($error)) {
      $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
mysql_query("INSERT INTO contact (name,batch,email,mobile) 
                VALUES('$name','$batch','$email','$mobile') ") or die(mysql_error());
      echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
      } elseif (!empty($success)) {
      echo $success;
      }
    ?>
这与

它应该是什么相反

if (!empty($error)) {
    ^
     // your database stuff here
}
应在错误为空时运行该查询

而不是在错误不为空时运行该查询。

if (empty($error)) {
      // now save to database    
 }

还要通过如何防止 PHP 中的 SQL 注入?

检查在

数据库中插入数据的条件。您正在检查是否(!empty($error))这应该表示存在错误。另外,由于$error是一个字符串,我建议您检查值if(trim($error) != "")而不是使用empty()

你应该使用else if来检查每个条件。

if(isset($POST['submit'])){
if(empty($_POST['email'])){
$error[] = "email is required";
}
elseif(empty($_POST['name'])){
$error[]= "name is required;";
}
...
else{
 $email = $_POST['email'];
 $name = $_POST['name'];
// do all the stuff here
}
}
// also correct !empty ()
mysql_query(" INSERT INTO contact (`name`,`batch`,`email`,`mobile`) 
            VALUES('".$name."','".$batch."','".$email."','".$mobile."');

您需要连接字符串。如果将$email放在引号中,它将被视为字符串而不是变量。