使用php进行表单验证和存储

时间:2014-03-14 20:10:44

标签: php html mysql forms validation

我有一项任务,我需要建立一个非常简单的网站,提示用户填写表格并提交。之后,将进行验证检查,并向他呈现成功信息(可能在不同的页面中)。将要存储表单输入的表的字段如下:

TABLE inquiries (
inquiry_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
submit_date DATETIME,
first_name VARCHAR(35),
last_name VARCHAR(35),
address VARCHAR(255),
postcode VARCHAR(8),
email VARCHAR(254),
phone VARCHAR(11),
wedding_date DATE,
wedding_location VARCHAR(50),
special_req TEXT
);

所以,基本上我的表单包含上面的所有内容,但是来自inquiry_id和submit_date。

最初,我通过输入以下

的HTML代码来验证我的表单
<form name = "Order Form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">

在我制作所有ckecks之前的PHP脚本中。这很好。

我的主要问题是将这些输入存储在给定的数据库中。现在,我已经尝试过了:

a)在关闭表单之前,我有这个php脚本:

        $connection=mysqli_connect("serverName","username","password","DB");
        if (mysqli_connect_errno())
        {
           echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
       date_default_timezone_set('Europe/London');
//I use a datepicker with the format mm/dd/yyy, but I want the format yyyy/mm/dd TIMESTAMP
       $currentDate = date('Y/m/d h:i:s a', time());
       $date = date('Y-m-d');
       mysqli_query($connection,"INSERT INTO inquiries 
        (submit_date, first_name, last_name, address,    postcode, email, phone,  wedding_date,     wedding_location, special_req)
        VALUES
        ('$currentDate', '$firstName', '$lastName', '$street', '$postcode', '$email',  '$mobileNumber', '$date', '$city', '$comments')");
       mysqli_close($connection);

这不起作用......

b)我创建了一个新的php文件并命名为#34; DBStore.php&#34;为了在之前的表单中调用它,所以现在action =&#34; DBStore.php&#34;。不幸的是,我无法访问数据库以查看输入是否存储正确,但我唯一得到的是空白页。

我希望将验证和商店合并到一个文件中,如果可能的话。

如何执行上一个(验证和存储,并显示正确的消息)?

我更愿意在两种情况下保持php编码。

验证的代码是:

<?php //code retrieved and customized from: http://www.w3schools.com/php/php_form_validation.asp and http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_required
              // define variables and set to empty values
            $firstNameError = $lastNameError = $streetError = $cityError = $postcodeError = $emailError = $mobileNumberError = $dateError = "";
            $firstName = $lastName = $street = $city = $postcode = $email = $mobileNumber = $date = "";
            if ($_SERVER["REQUEST_METHOD"] == "POST")
            {
                if (empty($_POST["firstName"]))
                {$firstNameError = "Please fill this field";}
                else
                {
                    $firstName = test_input($_POST["firstName"]);
                    // check if name only contains letters and whitespace
                    if (!preg_match("/^[a-zA-Z ]*$/",$firstName))
                    {
                        $firstNameError = "Please use only letters and white spaces"; 
                    }
                }
                if (empty($_POST["lastName"]))
                {$lastNameError = "Please fill this field";}
                else
                {
                    $lastName = test_input($_POST["lastName"]);
                    // check if name only contains letters and whitespace
                    if (!preg_match("/^[a-zA-Z ]*$/",$lastName))
                    {
                        $lastNameError = "Please use only letters and white spaces"; 
                    }
                }   
                if (empty($_POST["street"]))
                {$streetError = "Please fill this field";}
                else 
                {
                    // check if street address syntax is valid
                    $street = test_input($_POST["street"]);
                    if(!preg_match('/[^A-Za-z0-9]/', $street)){
                        $streetError = "Please use only letters, numbers and whitespaces";
                    }
                }   
                if (empty($_POST["city"]))
                {$cityError = "Please fill this field";}
                else
                {
                    // check if city syntax is valid
                    $city = test_input($_POST["city"]);
                    // check if name only contains letters and whitespace
                    if (!preg_match("/^[a-zA-Z ]*$/",$city))
                    {
                        $cityError = "Please use only letters and whitespaces"; 
                    }
                }
                if (empty($_POST["postcode"]))
                {$postcodeError = "Please fill this field";}
                else 
                {
                    //check if postcode syntax is valid
                    $postcode = test_input($_POST["postcode"]);
                    if(!preg_match('/[^A-Za-z0-9]*$/', $postcode)){
                        $postcodeError = "Please use only letters, numbers and whitespace";
                    }
                }
                if (empty($_POST["email"]))
                {$emailError = "Please fill this field";}
                else
                {
                    $email = test_input($_POST["email"]);
                    // check if e-mail address syntax is valid
                    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
                    {
                        $emailError = "Please rewrite your email address in the format a@b.code"; 
                    }
                }
                if (empty($_POST["mobileNumber"]))
                {$mobileNumberError = "Please fill this field";}
                else 
                {
                    $mobileNumber = test_input($_POST["mobileNumber"]);
                    // check if mobile number syntax is valid
                 if (!preg_match('/^\d+$/',$mobileNumber))
                    {
                    $mobileNumberError = "Please write only numbers";
                    }
                }
                if (empty($_POST["date"]))
                {$dateError = "Please fill this field";}
            //echo "I'm here";
            //exit();   
        }   
        function test_input($data)
        {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
        }
    ?>

完整的HTML表单是这样的:

<form name = "Order Form" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method = "post">--></form>
                <!--<form name = "Order Form" action = "DBStore.php" method = "post">-->
                <table>
                    <tr>
                        <td align = "right"><span class="error">* </span>First name: </td>
                        <!--Printing the field values after the validation, customization made based on http://www.w3resource.com/php/form/php-form-validation.php --> 
                        <td align = "left"><input type = "text" name = "firstName" value = "<?php echo $_POST['firstName']; ?>"/></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td align = "left"><span class="error"><?php echo $firstNameError;?></span></td>
                    </tr>
                    <tr>
                        <td align = "right"><span class="error">* </span>Last name: </td> 
                        <td align = "left"><input type = "text" name = "lastName" value = "<?php echo $_POST['lastName']; ?>"/></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td align = "left"><span class="error"><?php echo $lastNameError;?></span></td>
                    </tr>
                    <tr>
                        <td align = "right"><span class="error">* </span>Address: </td>
                        <td align = "left"><input type = "text" name = "street" value = "<?php echo $_POST['street']; ?>"/></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td align = "left"><span class="error"><?php echo $streetError;?></span></td>
                    </tr>
                    <tr>
                        <td align = "right"><span class="error">* </span>Postcode: </td>
                        <td align = "left"><input type = "text" name = "postcode" value = "<?php echo $_POST['postcode']; ?>"/></td>                
                    </tr>
                    <tr>
                        <td></td>
                        <td align = "left>"><span class="error"><?php echo $postcodeError;?></span></td>
                    </tr>
                    <tr>
                        <td align = "right"><span class="error">* </span>E-mail: </td>
                        <td align = "left"><input type = "text" name = "email" value = "<?php echo $_POST['email']; ?>"/></td>          
                    </tr>
                    <tr>
                        <td></td>
                        <td align = "left>"><span class="error"><?php echo $emailError;?></span></td>
                    </tr>
                    <tr>
                        <td align = "right"><span class="error">* </span>Contact number: </td>
                        <td align = "left"><input type = "text" name = "mobileNumber" value = "<?php echo $_POST['mobileNumber']; ?>"/></td>                
                    </tr>
                    <tr>
                        <td></td>
                        <td align = "left"><span class="error"><?php echo $mobileNumberError;?></span></td>
                    </tr>
                    <tr>
                    <tr>
                        <td align = "right"><span class="error">*</span>Wedding date: </td>
                        <td align = "left"><input type = "text" name = "date" id ="date" value = "<?php echo $_POST['date']; ?>"/></td> 
                    </tr>
                    <tr>
                        <td></td>
                        <td align = "left"><span class="error"><?php echo $dateError;?></span></td>
                    </tr>
                    <tr>
                        <td align = "right"><span class="error">* </span>Wedding location: </td>
                        <td align = "left"><input type = "text" name = "city" value = "<?php echo $_POST['city']; ?>"/></td>            
                    </tr>
                    <tr>
                        <td></td>
                        <td align = "left>"><span class="error"><?php echo $cityError;?></span></td>
                    </tr>
                    <tr>
                        <td align="right"> Leave your comments:</td>
                        <td><textarea rows = "7" cols = "30" name = "comments" id = "comments" value = "<?php echo $_POST['comments']; ?>"/></textarea></td>
                    </tr>
                </table><br>
                <input type = "submit" name = "submit" value = "Submit Details" style ="margin-left: 145px;"/>
                <input type = "reset" value = "Clear Form"/>
            </div>
</form>

谢谢:)

0 个答案:

没有答案