将表数据插入到DB中忽略空检查,仍然插入


Inserting table data into a DB ignores !empty check and still inserts

我有多个表,用户可以在其中输入数据。如果用户选择,他们不必在每个表中输入数据,并且在遍历数据并开始将其插入数据库之前,我会检查字段是否为空。

下面是其中一个表的样子:

<table id="budget_table">
<thead>
    <tr>
        <th>Roofs</th>
        <th>Area</th>
        <th>Recommendation</th>
        <th>Budget</th>
    </tr>
</thead>
<tbody id="budget_tb">
    <tr id="budget_row0">
        <td><input id="budget-roofs" name="budget-roofs[]" placeholder="Entire Roof Area"></td>
        <td><input id="budget-area" name="budget-roof-area[]" placeholder="Approx. 1,000 Sq. Ft."></td>
        <td><input id="budget-recommendation" name="budget-recommendation[]" placeholder="Roof Repairs & Maintenance"></td>
        <td><input id="budget-amount" name="budget-amount[]" placeholder="$1,500.00 to $2,500.00"></td>
    </tr>
</tbody>
</table>
<input type="submit" value="Create" name="submit">

当用户单击submit时,我将检查第一个输入字段是否为空,如果为空,我不想做任何事情。如果在输入字段中有内容,那么我想将该数据转储到数据库中。

下面是我的PHP代码:
var_dump($_POST['budget-roofs']); //I added this to see what was going on
if(!empty($_POST['budget-roofs'])){ 
    //foreach budget row insert data
    foreach ($_POST['budget-roofs'] as $index => $roofs) {
        $area = $_POST['budget-roof-area'][$index];
        $recommendations = $_POST['budget-recommendation'][$index];
        $amount = $_POST['budget-amount'][$index];
        //insert queries
    }
}

如果我在输入字段中没有输入任何内容,它会向数据库提交一个空字符串。

我使用var_dump来检查它是否真的为空,以及为什么它忽略了我的检查。这是显示给我的:

array (size=1)
  0 => string '' (length=0)

所以它显示我有一个大小为1(所以它不是空的,这就是为什么我的检查被忽略)。

然而,我不确定为什么它有一个空字符串?

我试着拿出我的placeholder属性,因为我认为这可能会导致一些事情,但这也不是问题。

是否有更好的方法来检查,看看我的输入字段是否为空,并确保空字符串不被转储到数据库中?

这个空字符串是从哪里来的?

然而,我不确定为什么它有一个空字符串?

提交表单中的输入字段,如果它们不包含数据(由用户输入),则提交为空。

<?php
var_dump($_POST);
?>
<form method="post" action="example.php">
    <input type="text" name="arr" value="">
    <input type="submit" name="submit" value="Submit">
</form>

如果您提交上面的表单为空:

array(2) { ["arr"]=> string(0) "" ["submit"]=> string(6) "Submit" }

您至少有一个预算顶部的数组元素,因为它存在于表单中。<input id="budget-roofs" name="budget-roofs[]" placeholder="Entire Roof Area">如果你不输入输入,它仍然是空的提交。

有没有更好的方法来检查我的输入字段是否空的,并确保空字符串不被转储到数据库?

你必须单独检查每个元素。

foreach ($_POST['budget-roofs'] as $index => $roofs) {
   if (! empty($roofs) 
     // Insert here. But remember to check the other fields, they may be empty as well.