动态空字段不应存储在数据库中

时间:2014-04-02 17:32:11

标签: php mysql arrays pdo foreach

这里我成功地将一些数组值存储到数据库中。但是,我在这里遇到了问题。例如:我有四个输入文本字段。假设用户填写了三个文本字段,剩下的一个字段为空。当我执行这段代码时,我的db表中有4行。 包含值的3行和不包含值的一行(空字段)。 (我不需要一行没有价值)

但是,如果用户没有输入一个字段,那么该字段不应该存储在数据库中。怎么做?我在下面发布了我的代码和图片。

<?php
include('config.php');

if(isset($_POST['submit']))
{
    $cqty = $_POST['qty'];

    foreach( $cqty as $key => $n ) 
    {
        echo $n ."<br/>";
        try
        {
            $stmt = $conn->prepare("INSERT INTO testing ( qty ) VALUES ( :n )");
            $conn->errorInfo();
            $stmt->bindParam(':n', $n, PDO::PARAM_STR);
            $stmt->execute();
        }
        catch (PDOException $e)
        {
            $e->getMessage();
        }
    }
    if($stmt)
        {
            echo "inserted";
        }
        else
        {
             die(mysql_error());
        }
}
?>

<form action="db.php" method="post">
    qty : <input type="text" name="qty[]" /><br />
    <input type="submit" name="submit" value="Submit" />
</form>

enter image description here

1 个答案:

答案 0 :(得分:1)

使用empty检查$n是否为空。使用continue跳过该迭代的foreach循环中的其余指令。

foreach( $cqty as $key => $n ) 

    if (empty($n)) continue;
    echo $n ."<br/>";
         try ...