您好我有一个名为tables
的表,其中包含9个字段(`id,first,second,third,4th,5th,six,seven,eight),如果所有这些字段都不为空,我想将它作为新记录插入到同一个表中。这是我现在的代码:
$db = new db();
$bind = array(
":tid" => "1"
);
$results = $db->select("tables", "tableID = :tid", $bind);
foreach ($results as $r) {
$tableID = $r['id'];
$l1_1 = $r['first'];
$l1_2 = $r['second'];
$l1_3 = $r['third'];
$l1_4 = $r['fourth'];
$l1_5 = $r['fifth'];
$l1_6 = $r['sixth'];
$l1_7 = $r['seventh'];
$l1_8 = $r['eight'];
}
if($l1_1 != "" AND $l1_2 != "" AND $l1_3 != "" AND $l1_4 != "" AND $l1_5 != "" AND $l1_6 != "" AND $l1_7 != "" AND $l1_8 != "")
{
$db->insert("tables", array(
"first" => $l1_1,
"second" => $l1_2,
"third" => $l1_3,
"fourth" => $l1_4,
));
//insert 2nd record
$db->insert("tables", array(
"first" => $l1_5,
"second" => $l1_6,
"third" => $l1_7,
"fourth" => $l1_8,
));
}
我还有一个很长的代码,它的作用摘要是检查字段是否为空并在那里插入数据,直到所有字段都被填满。输入最后一个数据时,将执行上面的代码。输入最后一个数据时,它将执行上面的代码,检查所有字段是否为空并插入新数据。此代码有效,但插入的最后一个数据在插入的新记录中显示为空白。
我知道我的解释很模糊,但请问我想知道什么。
答案 0 :(得分:2)
我相信你的答案在于你的If声明。您正在检查字段是""还是空白。这是不正确的,因为它们在数据库中可能为NULL。有一个答案可以解释如何解决它。
Better way to check variable for null or empty string?
按如下方式更改您的代码:
if(isset($l1_1) && trim(($l1_1) != ''
AND isset($l1_2) && trim(($l1_2) != ''
AND isset($l1_3) && trim(($l1_3) != ''
AND isset($l1_4) && trim(($l1_4) != ''
AND isset($l1_5) && trim(($l1_5) != ''
AND isset($l1_6) && trim(($l1_6) != ''
AND isset($l1_7) && trim(($l1_7) != ''
AND isset($l1_8) && trim(($l1_8) != '')