【问题标题】:Form Validation and Submission to database表单验证和提交到数据库
【发布时间】:2015-02-19 05:35:11
【问题描述】:

我正在做一个项目,该项目有一个表单,它应该自我验证,然后将数据提交到 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();
?>

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

【问题讨论】:

  • 那么,出了什么问题?此外,mysql_* 已折旧。您应该考虑使用 MySQLi 或 PDO。
  • 如果一切正常,请调用您的验证脚本
  • 告诉我们什么是错误。
  • @Yash 注意:“这可以很好地验证表单,但我面临的问题是在验证后将表单提交到数据库。”
  • 错误是我无法将验证脚本和upload_file.php 链接在一起。如果我将验证脚本放在 upload_file.php 页面中,则无需执行验证脚本即可提交数据。所以我必须将验证脚本放到表单存在的同一页面,即 index.php。现在我真正想要的是在验证后表单应该提交到数据库。这就是问题发生的地方。请帮帮我。

标签: php jquery mysql forms validation


【解决方案1】:

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

include 'upload_file.php'

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

首先请注意,对于任何语法错误,我深表歉意。那是徒手画的。

其次,我对您的代码有几点建议:

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

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

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

希望这就是你所需要的。

【讨论】:

  • 我应该把它包含在我的验证文件中吗?我试图这样做,但它显示语法错误。你能告诉我应该在哪里包含它以及如何包含它吗?
  • 是的,上传脚本已包含在您的验证脚本中。我假设此时您已经按照建议执行了验证,那么您遇到的错误是什么?
  • 意外如果在第 121 行...类似这样的东西。您能否将我的验证脚本与您的代码一起重新发布在其中,以便它可以正常工作而不会出现任何语法错误。我将复制并粘贴它,然后让它工作。
  • 假设两个脚本都在同一个目录中,您可以复制粘贴我在验证脚本底部放置的内容。我相信问题可能是缺少$,我刚刚修复了它。
猜你喜欢
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 2013-12-31
  • 1970-01-01
相关资源
最近更新 更多