表单将空数据插入数据库

时间:2019-07-19 11:25:49

标签: php mysql

每当我提交带有空输入的表单时,它会将空输入发送到我的数据库。直到我将htmlentities()用于其功能之后,该表单才能正常工作。

我使用gettype()函数返回插入变量中的内容,并返回“字符串”,但是当我从浏览器中检查代码时,表中什么都看不到。

This is the code snippet and the form processing code

<?php
$errors = [];
$missing = [];

if(isset($_POST['sendFirm']) ){

$expected = array('firmName','country','state','email','phoneNumber');
$required = array('firmName','country','state','phoneNumber');

<?php

foreach ($_POST as $key => $value) {

        if(is_array($value)){
            $value = $value;
            }else{
            $value = trim($value);
            }

        if(empty($value) && in_array($key, $required)){
        $missing[] = $key;
        $$key = '';
        }elseif(in_array($key, $expected)){
        $$key = "$value";
        }
}

?>
}



?>
<?php 
        if($errors || $missing){
     ?>
     <p>Please fix the following items</p>
    <?php } ?>
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<div class="form-group">
<label>Compnay Name
<?php if($missing && in_array('firmName', $missing)) { ?>
    <span class="text-danger">Please enter firm name</span>
<?php } ?>
</label>
<input class="form-control" type="text" name="firmName" id="firmName" placeholder="Company Name"
<?php
if($errors || $missing){
    print 'value="' . htmlentities($firmName) . '"';
}
>
<button class="btn btn-primary" type="submit" 
name="sendFirm">Submit</button>
</form>
?>
>


<?php


if(isset($_POST['sendFirm'])){
    try {
    $connectToFirms = new 
PDO('mysql:host=localhost;dbname=firms','root','2332');
    $connectToFirms->setAttribute(PDO::ATTR_ERRMODE, 
PDO::ERRMODE_EXCEPTION);

    $prepInsertion = $connectToFirms->prepare('INSERT INTO contractors 
VALUES (null,?,?,?,?,?)');

    $prepInsertion->execute(array($firmName, $country, $state, $email, 
$phoneNumber));

}catch (PDOException $e) {
    print "An error occure: " . $e->getMessage();
}
}


?>

仅当输入不为空且该输入也位于$ expected []中时,才希望该表单将输入插入数据库中。

1 个答案:

答案 0 :(得分:0)

不插入数据

如果未提供预期的输入,我将停止整个数据插入。我还将输入数据一一发送到PHP,因此您可以更好地了解代码。良好的概述=更少的错误;)

尝试一下:

<?php

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

    $firmname = htmlentities($_POST["firmName"], ENT_QUOTES);

    $country = htmlentities($_POST["country"], ENT_QUOTES);

    $state = htmlentities($_POST["state"], ENT_QUOTES);

    $pn = htmlentities($_POST["phoneNumber"], ENT_QUOTES);

// LET'S START THE VALIDATION

    // if the required fields are not empty, insert data
    if (!empty($firmname) && !empty($country) && !empty(state) && !empty($pn)) {

        // insert data

    } else { // else stop insertion and return error message

        // return error message

    }
} else {
    // redirect...
}

希望我能正确理解您的问题,并且可以为您提供帮助。