【问题标题】:dynamic empty field should not be stored in database动态空字段不应存储在数据库中
【发布时间】:2014-05-14 04:05:44
【问题描述】:

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

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

<?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>

【问题讨论】:

    标签: php mysql arrays pdo foreach


    【解决方案1】:

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

    foreach( $cqty as $key => $n ) 
    
        if (empty($n)) continue;
        echo $n ."<br/>";
             try ...
    

    【讨论】:

      猜你喜欢
      • 2011-03-18
      • 1970-01-01
      • 2012-08-29
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      相关资源
      最近更新 更多