当每次操作都在同一页上时,如何验证表单


How to validate forms when everytime action is on same page

我正在尝试在验证表单后插入表单字段值。我开发了一个单独的php文件validate1.php,将表单字段值插入数据库和另一个描述表单的文件中,其验证在connection.php 中

当我运行connection.php时,表单字段只验证一次,在提交表单之后,我输入任何内容。这不应该发生。

我的connection.php是

<html>
<head>
    <title></title>
    <style> .error {color:#ff0000;} </style>
</head>
<body>
    <?php 
        $companyNameErr = $addressErr = $emailErr = $contactErr = "";
        $companyName = $address = $email = $contact = $description = "";
        function test_data($data)
        {
            $data=trim($data);
            $data=stripslashes($data);
            $data=htmlspecialchars($data);
            return $data;
        }
        $errors = array();
        if ( $_SERVER["REQUEST_METHOD"] =="POST" )
        {
            $companyName=$_POST["companyName"];
            if( empty($companyName) )
            {
                $companyNameErr = "Please Enter Company Name";
                $errors[]= $companyNameErr ;
            }
            else
            {
                if( !preg_match("/^[a-zA-Z ]*$/",$companyName) )
                {
                    $companyNameErr = "Invalid Company Name";
                    $errors[]= $companyNameErr ;
                }
                else
                {
                    $companyName=test_data($companyName);
                }
            }
            $address=$_POST["address"];
            if( empty($address) )
            {
                $addressErr = "Please Enter Address";
                $errors[]= $addressErr ;
            }
            else
            { 
                $address=test_data($address);
            }
            $email=$_POST["email"];
            if( empty($email) )
            {
                $emailErr = "Please Enter Email";
                $errors[]= $emailErr ;
            }
            else
            {
                if( !filter_var($email, FILTER_VALIDATE_EMAIL) )
                {
                    $emailErr = "Invalid Email";
                    $errors[]= $emailErr ;
                }
                else
                {
                    $email=test_data($email);
                }   
            }       
            $contact=$_POST["contact"];
            if( empty($contact) )
            {
                $contactErr = "Please Enter Contact Number";
                $errors[]= $contactErr ;
            }
            else
            { 
                if( !preg_match("/^[0-9]*$/",$contact ) )
                {
                    $contactErr = "Invalid Contact";
                    $errors[]= $contactErr ;
                }
                else
                {
                    $contact=test_data($contact);
                }   
            }
    }
    ?>
    <form name="myform" method="post" action="<?php if(empty($errors)){ echo $_SERVER["PHP_SELF"]; }else{ echo "validate1.php"; }?>" >
        <table>
            <tr>
                <td>Company Name</td>
                <td><input type="text" name="companyName" value ="<?php if(isset($_POST['companyName']) && empty($companyNameErr)){ echo $_POST['companyName'];} else {echo '';}?>" required ><span class="error"><sup>*</sup><?php echo $companyNameErr; ?></span></td>
            </tr>
            <tr>
                <td>Address</td>
                <td><input type="text" name="address" value ="<?php if(isset($_POST['address']) && empty($addressErr)){ echo $_POST['address'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php echo $addressErr; ?></span></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="text" name="email" value ="<?php if(isset($_POST['email']) && empty($emailErr)){ echo $_POST['email'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php echo $emailErr; ?></span></td>
            </tr>
            <tr>
                <td>Contact</td>
                <td>+91-<input type="text" name="contact" value ="<?php if(isset($_POST['contact']) && empty($contactErr)){ echo $_POST['contact'];} else {echo '';}?>" required maxlength="10" minlength="10"><span class="error"><sup>*</sup><?php echo $contactErr; ?></span></td>
            </tr>
            <tr>
                <td>Description</td>
                <td><textarea name="description" cols="60" rows="3"></textarea></td>
            </tr>
        </table>
        <input type="submit" name="submit" value="submit">
    </form>
</body>

Validate1.php是

<html>
<head>
    <title></title>
</head>
<body>    
<?php 
    $servername="localhost";
    $username="root";
    $password="";
    $conn = new mysqli($servername, $username, $password, 'mydatabase');
    if ($conn->connect_error)
    {
        die("Connection failed: " . $conn->connect_error);
    }
    $conn->query("CREATE DATABASE IF NOT EXISTS `MyDataBase`"); 
    $conn->query("CREATE TABLE IF NOT EXISTS MyDataBase.company_details( `comp_id` INT AUTO_INCREMENT PRIMARY KEY,`company_name` VARCHAR(50) NOT NULL,`address` VARCHAR(70) NOT NULL,`email` VARCHAR(30) NOT NULL,`contact` INT(13) NOT NULL,`description` VARCHAR(150))");
    $conn->query("INSERT INTO company_details (company_name, address, email, contact, description ) VALUES ( '".$_POST['companyName']."', '".$_POST['address']."', '".$_POST['email']."', '".$_POST['contact']."', '".$_POST['description']."')");
    $conn->close();
?>
</body>

尝试以下代码

N: B:确保在发布表单数据时使用了sql注入预防技术

connection.php

<?php 
session_start();
    $companyName = $address = $email = $contact = $description = "";
    function test_data($data)
    {
        $data=trim($data);
        $data=stripslashes($data);
        $data=htmlspecialchars($data);
        return $data;
    }
    $_SESSION['error'] = array();
    $_SESSION['resend'] = array();
    if ( $_SERVER["REQUEST_METHOD"] =="POST")
    {
        $companyName=$_POST["companyName"];
        if(empty($companyName) )
        $_SESSION['error']['companyNameErr'] = "Please Enter Company Name";
        else
        {
            if( !preg_match("/^[a-zA-Z ]*$/",$companyName) )                
                $_SESSION['error']['companyNameErr'] = "Invalid Company Name";                
            else
                $_SESSION['resend']['companyName'] = test_data($companyName);                
        }
        $address=$_POST["address"];
        if(empty($address) )            
            $_SESSION['error']['addressErr'] = "Please Enter Address";            
        else
            $_SESSION['resend']['address'] = test_data($address);
        $email=$_POST["email"];
        if(empty($email))            
            $_SESSION['error']['emailErr'] = "Please Enter Email";
        else
        {
            if( !filter_var($email, FILTER_VALIDATE_EMAIL) )                
                $_SESSION['error']['emailErr'] = "Invalid Email";
            else
                $_SESSION['resend']['email'] = test_data($email);                    
        }
        $contact=$_POST["contact"];
        if(empty($contact))
            $_SESSION['error']['contactErr'] = "Please Enter Contact Number";                
        else
        { 
            if( !preg_match("/^[0-9]*$/",$contact ) )                
                $_SESSION['error']['contactErr'] = "Invalid Contact";
            else                
                $_SESSION['resend']['contact'] = test_data($contact);                   
        }
        $description=$_POST["description"];
        $_SESSION['resend']['description'] = test_data($description); 
        if(empty($_SESSION['error'])){
            header('location:validate1.php');    
        exit;
        }
    }
?>
<html>
<head>
    <title></title>
    <style> .error {color:#ff0000;} </style>
</head>
<body>
    <form name="myform" method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" >
        <table>
            <tr>
                <td>Company Name</td>
                <td><input type="text" name="companyName" value ="<?php if(isset($_SESSION['resend']['companyName']) && empty($_SESSION['error']['companyNameErr'])){ echo $_SESSION['resend']['companyName'];} else {echo '';}?>" required ><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['companyNameErr'])) echo $_SESSION['error']['companyNameErr']; ?></span></td>
            </tr>
            <tr>
                <td>Address</td>
                <td><input type="text" name="address" value ="<?php if(isset($_SESSION['resend']['address']) && empty($_SESSION['error']['addressErr'])){ echo $_SESSION['resend']['address'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['addressErr'])) echo $_SESSION['error']['addressErr']; ?></span></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="text" name="email" value ="<?php if(isset($_SESSION['resend']['email']) && empty($_SESSION['error']['emailErr'])){ echo $_SESSION['resend']['email'];} else {echo '';}?>" required><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['emailErr'])) echo $_SESSION['error']['emailErr']; ?></span></td>
            </tr>
            <tr>
                <td>Contact</td>
                <td>+91-<input type="text" name="contact" value ="<?php if(isset($_SESSION['resend']['contact']) && empty($_SESSION['error']['contactErr'])){ echo $_SESSION['resend']['contact'];} else {echo '';}?>" required maxlength="10" minlength="10"><span class="error"><sup>*</sup><?php if(isset($_SESSION['error']['contactErr'])) echo $_SESSION['error']['contactErr']; ?></span></td>
            </tr>
            <tr>
                <td>Description</td>
                <td><textarea name="description" cols="60" rows="3"><?php if(isset($_SESSION['resend']['description'])) echo $_SESSION['resend']['description'];?></textarea></td>
            </tr>
        </table>
        <input type="submit" name="submit" value="submit">
    </form>
</body>
</html>

Validate1.php

<?php 
session_start();
if(isset($_SESSION['resend'])){ 
    $servername="localhost";
    $username="root";
    $password="";
    $conn = new mysqli($servername, $username, $password, 'test');
    if ($conn->connect_error)
    {
        die("Connection failed: " . $conn->connect_error);
    }
    //$conn->query("CREATE DATABASE IF NOT EXISTS `MyDataBase`"); 
    $conn->query("CREATE TABLE IF NOT EXISTS test.company_details( `comp_id` INT AUTO_INCREMENT PRIMARY KEY,`company_name` VARCHAR(50) NOT NULL,`address` VARCHAR(70) NOT NULL,`email` VARCHAR(30) NOT NULL,`contact` INT(13) NOT NULL,`description` VARCHAR(150))");
    $result = $conn->query("INSERT INTO company_details (company_name, address, email, contact, description ) VALUES ( '".$_SESSION['resend']['companyName']."', '".$_SESSION['resend']['address']."', '".$_SESSION['resend']['email']."', '".$_SESSION['resend']['contact']."', '".$_SESSION['resend']['description']."')");
    $conn->close();
    unset ($_SESSION['resend']);
    unset ($_SESSION['error']);
    header('location:connection.php'); 
    exit;
}
?>
<html>
<head>
    <title></title>
</head>
<body>   
</body>
</html>