Here I'm stored some array values into database successfully. But, I have a problem here. For example : I have four input textfields. Assume if user filled three textfields and remaining one field is empty. When I execute this code I got 4 rows in my db table. 3 rows with values and one row without a value (empty field). (I DONT NEED THAT ONE ROW WITHOUT A VALUE)
在这里,我成功地将一些数组值存储到数据库中。但是,我在这里遇到了问题。例如:我有四个输入文本字段。假设用户填写了三个文本字段,剩下的一个字段为空。当我执行这段代码时,我的db表中有4行。带有值的3行和没有值的一行(空字段)。 (我不需要一行没有价值)
But, I need if user didn't entered one field that field should not be stored in database. How to do that? I have posted my codes and image below.
但是,如果用户没有输入一个字段,那么该字段不应该存储在数据库中。怎么做?我在下面发布了我的代码和图片。
<?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());
}
}
?>
and
和
<form action="db.php" method="post">
qty : <input type="text" name="qty[]" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
1 个解决方案
#1
1
Use empty
to check if $n
is empty. Use continue
to skip the rest of the instruction in the foreach loop for that iteration.
使用empty来检查$ n是否为空。继续跳过该迭代的foreach循环中的其余指令。
foreach( $cqty as $key => $n )
if (empty($n)) continue;
echo $n ."<br/>";
try ...
#1
1
Use empty
to check if $n
is empty. Use continue
to skip the rest of the instruction in the foreach loop for that iteration.
使用empty来检查$ n是否为空。继续跳过该迭代的foreach循环中的其余指令。
foreach( $cqty as $key => $n )
if (empty($n)) continue;
echo $n ."<br/>";
try ...