验证后将数据插入数据库

时间:2012-03-21 16:41:37

标签: php mysql

我正在以php形式工作,我用正则表达式验证了这个领域。验证工作正常,但我想在验证完成后将数据插入数据库,没有错误我不知道如何引用它?

我面临一个问题,每次点击提交时数据都会将空记录插入数据库。此外,我想在完成插入后重定向到感谢页面。

我非常感谢你的帮助和建议。

这是我的代码

<?php
  $errname     = "";
  $errage      = "";
  $errmobile   = "";

  if($_POST["ac"]=="login"){
    // Full Name must be letters, dash and spaces only
      if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["name"]) === 0)
      $errname = '<p class="errText">Please enter your full name </p>';
    // age must be 2 digits
    if(preg_match("/^\d{2}$/", $_POST["age"]) === 0)
      $errage = '<p class="errText">Age must be 2 digits</p>';
              // Mobile mask 050-0000000
    if(preg_match("/^\d{3}-\d{7}$/", $_POST["mobile"]) === 0)
      $errmobile = '<p class="errText">Mobile must be in this format: 050-0000000</p>';


      // contact to database

$connect = mysql_connect("localhost", "root", "") or die ("Error , check your server connection.");

mysql_select_db("career_system");

 //Get data in local variable

$v_name=$_POST['name'];

$v_age=$_POST['age'];

$v_gender=$_POST['gender'];

$v_mobile =$_POST['mobile'];


$query="insert into applicant(name, age, gender, mobile ) values ('$v_name', '$v_age', '$v_gender','$v_mobile ')";

mysql_query($query)  or die(mysql_error());
}
echo "Your information has been received"; 
      }


  ?>

</head>

<body>
<div align="center">
  <p>&nbsp;</p>
</div>
<form name="form1" action="<?php echo $PHP_SELF; ?>" method="POST">
  <p>
    <input type="hidden" name="ac" value="login">
  </p>
  <table width="485" border="0">
      <tr>
        <td width="48">Full Name</td>
        <td width="150"><input name="name" type="text" id="name" value="<?php echo      $_POST["name"]; ?>"></td>
        <td width="273"><?php  if(isset($errname)) echo $errname; ?></td>
      </tr>
      <tr>
        <td>Age</td>
        <td><input name="age" type="text" id="age" value="<?php echo $_POST["age"]; ?>"></td>
        <td><?php  if(isset($errage)) echo $errage; ?></td>
      </tr>
      <tr>
        <td>Gender</td>
        <td><input name="gender" type="radio" value="Male" checked>
          Male 
          <input name="gender" type="radio" value="Female">
          Female</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>Mobile</td>
        <td><input name="mobile" type="text" id="mobile" value="<?php echo $_POST["mobile"]; ?>"></td>
        <td><?php  if(isset($errmobile)) echo $errmobile; ?></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td><input type="submit" name="Submit" value="Submit">
        <input name="reset" type="reset" id="reset" value="Reset"></td>
        <td>&nbsp;</td>
      </tr>
  </table>
</form>

3 个答案:

答案 0 :(得分:2)

您可以简单地使用$errors数组,并在插入之前检查其空虚:

$errors = array();

if ($_POST["ac"]=="login") {

    if (!preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST['name']))
        $errors['name'] = '<p class="errText">Please enter your full name </p>';

    if (!preg_match("/^\d{2}$/", $_POST['age']))
        $errors['age'] = '<p class="errText">Age must be 2 digits</p>';

    // etc...

    if (!$errors) {
        $query = "
            insert into applicant 
            (name, age, gender, mobile ) 
            values 
            (
            '".mysql_real_escape_string($v_name)."', 
            '".mysql_real_escape_string($v_age)."', 
            '".mysql_real_escape_string($v_gender)."', 
            '".mysql_real_escape_string($v_mobile)."'
            )
        ";

        mysql_query($query);
    }

    // etc...
}

// Later in your HTML:

<tr>
    <td>Mobile</td>
    <td><input name="mobile" type="text" id="mobile" value="<?php echo $_POST["mobile"]; ?>"></td>
    <td><?php  if(isset($errors['mobile'])) echo $errors['mobile'] ?></td>
</tr>

确保在将数据发送到数据库之前转义数据(因此,mysql_real_escape_string调用)!一个重要的建议是实际放弃mysql_函数,因为它们已经过时了。你应该使用PDO。它更容易,更高效,并且可以轻松消除大部分SQL注入威胁:

try {
    $dbh = new PDO("mysql:host=localhost;dbname=mydb", 'username', 'password');
} catch(PDOException $e) {
    die('Could not connect to database!');
}

$stm = $dbh->prepare('INSERT INTO applicant (name, age, gender, mobile ) VALUES (?, ?, ?, ?)');
$stm->execute(array($v_name, $v_age, $v_gender, $v_mobile));

答案 1 :(得分:1)

在申请人之后添加空格 - INSERT INTO申请人(name, age, gender, mobile )

此外,您的代码不安全,您的数据库现在容易受到攻击。在将它们插入数据库之前,请确保将所有字符串转义!

http://phptutorial.info/?mysql-real-escape-string

答案 2 :(得分:-1)

如下:

  if($_POST["ac"]=="login"){
    // Full Name must be letters, dash and spaces only
      if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["name"]) === 0)
      $errname = '<p class="errText">Please enter your full name </p>';
    // age must be 2 digits
    if(preg_match("/^\d{2}$/", $_POST["age"]) === 0)
      $errage = '<p class="errText">Age must be 2 digits</p>';
              // Mobile mask 050-0000000
    if(preg_match("/^\d{3}-\d{7}$/", $_POST["mobile"]) === 0)
      $errmobile = '<p class="errText">Mobile must be in this format: 050-0000000</p>';


      // contact to database

$connect = mysql_connect("localhost", "root", "") or die ("Error , check your server connection.");

mysql_select_db("career_system");

 //Get data in local variable

$v_name=$_POST['name'];

$v_age=$_POST['age'];

$v_gender=$_POST['gender'];

$v_mobile =$_POST['mobile'];

if($errname != "" || $errage != "" || $errmobile != "")
   echo "Error!";
else{

$query="insert into applicant(name, age, gender, mobile ) values ('$v_name', '$v_age', '$v_gender','$v_mobile ')";

    mysql_query($query)  or die(mysql_error());
}
}

为了您自己的安全,在将发布的值存储到数据库中时,请始终使用以下命令检查它们不是某种类型的攻击(例如SQL注入):

mysql_real_escape_string(param);