php - 表单验证和提交到数据库

标签 php jquery mysql forms validation

我正在开发一个项目,该项目有一个 FORM,它应该验证自身,然后将数据提交到 MySQL 数据库。但我面临一个错误。

这是表格

`

 <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">

    <table style="line-height: 50px;">
        <tr>
          <th>Name&nbsp;&nbsp;&nbsp;</th>
          <td><input type="text" name="name" placeholder="Your Name" style="height:30px; border:1px; width:300px; border-radius:5px; text-indent:15px"><span class="error">* <?php echo $nameErr;?></span></td>
        </tr>
        <br>
        <tr>
          <th>Phone&nbsp;&nbsp;&nbsp;</th>
          <td><input type="text" name="contact" placeholder="Your Contact Number" style="height:30px; border:1px; width:300px; border-radius:5px; text-indent:15px"><span class="error">* <?php echo $contactErr;?></span></td>
        </tr>
        <tr>
          <th>City&nbsp;&nbsp;&nbsp;</th>
          <td><input type="text" name="city" placeholder="Your City Name" style="height:30px; border:1px; width:300px; border-radius:5px; text-indent:15px"><span class="error">* <?php echo $cityErr;?></span></td>
        </tr>
        <tr>
          <th>Service&nbsp;&nbsp;&nbsp;</th>
          <td><select name="service" autocomplete="off" style="height:30px; border:1px; width:300px; border-radius:5px; text-indent:15px">
              <option value="">Select your service</option>
              <option value=service1>Service 1</option>
              <option value=service2>Service 2</option>
              <option value=service3>Service 3</option>
              <option value=service4>Service 4</option>
              </select><span class="error">* <?php echo $serviceErr;?></span></td>
        </tr>
    </table>
    <input type="submit" name="submit" value="Submit" style="height: 40px; width: 140px; border-radius: 5px; margin-left: 140px;margin-top: 20px;">
    </form>

`

这是验证脚本

`

<?php 
    // define variables and set to empty values
$nameErr = $contactErr = $cityErr = $serviceErr = "";
$name = $contact = $city = $service = "";


if ($_SERVER["REQUEST_METHOD"] == "POST") {

   if (empty($_POST["name"])) {
     $nameErr = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
       $nameErr = "Only letters and white space allowed";
     }
   }

   if (empty($_POST["contact"])) {
     $contactErr = "Contact is required";
   } else {
     $contact = test_input($_POST["contact"]);
     // check if contact number is well-formed
     if (!preg_match("/^[0-9+]*$/",$contact)) {
       $contactErr = "Phone number should contain only numbers";
     }
   }

   if (empty($_POST["city"])) {
     $cityErr = "City is required";
   } else {
     $city = test_input($_POST["city"]);
     // check if city is valid
     if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
       $cityErr = "Only letters and white space allowed";
     }
   }

   if (empty($_POST["service"])) {
     $serviceErr = "Service is required";
   } else {
     $service = test_input($_POST["service"]);
   }
 }

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}

?>

`

这很好地验证了表单,但我面临的问题是验证后将表单提交到数据库。

这是我的 upload_file.php 代码。

<?php

$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password="morningstar"; // Mysql password 
$db_name="infoline"; // Database name 
$tbl_name="user_profile"; // Table name 

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form 
$name=$_POST['name'];
$city=$_POST['city'];
$contact=$_POST['contact'];
$service=$_POST['service'];


// Insert data into mysql 
$sql="INSERT INTO user_profile(name, city, contact, service)VALUES('$name', '$city', '$contact', '$service')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful". 
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='index.php'>Back to main page</a>";
}

else {
echo "ERROR";
}
?> 

<?php 
// close connection 
mysql_close();
?>

谁能帮我解决这个问题吗?我想在正确验证后将表单提交到数据库。请帮帮我。

最佳答案

如果我理解正确,那么您只是不知道如何调用另一个文件。我建议将其变成一个函数,包括,然后调用它。像这样的事情:

include 'upload_file.php'

if($nameErr == $contactErr == $cityErr == $serviceErr == ""){
    upload_file($_POST['name'], $_POST['city'], $_POST['contact'], $_POST['service'])
}

首先请注意,我对任何语法错误表示歉意。这是徒手的。

其次,我对您的代码有一些建议:

  • 不要使用 mysql_* 函数,因为它们已被贬值。我喜欢 PDO,所以这就是我建议研究的内容。 (只需 Google 一下,就有很多)这还允许您使用准备好的语句,这是 mysql_* 函数缺少的最大的东西之一。

  • 由于您多次使用 POST 数据,因此请将它们放入局部变量中以开始使用。它将使您的代码简短、清晰、更易于阅读,并且如果您更改了字段的名称,将来也必须更容易更新。

  • 将所有错误放入一个字符串中。这样,如果成功,您只需检查一件事,如果失败,您只需将一件事发送回用户。

希望这就是您所需要的。

关于php - 表单验证和提交到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27580334/

相关文章:

javascript - 使用 JavaScript 将 div 转换为链接,数量有限。有类且没有 id

php - 将 SQL 表 ID 转换为 PHP 中的另一个字段

mysql - 使用子选择的MySQL查询需要使用联接或存在

php - 从 WP_List_Table 验证随机数

php - 在 mysql 数据库中保护用户密码的最佳方法?

jQuery 检查表单输入是否为空(除了一个)

jquery - 在 Select(DropDown) 更改事件上重新初始化 Jquery DataTable

php - 在 "IN CLAUSE"mysql php 中返回 null 或空字符串

PHP代码没有被执行,但是代码显示在浏览器源代码中

php - Mysql:从父表中选择,仅当子表有行时