我在这里回答了我的第一个问题:link
我的扩展问题是,我可以成功将行更新到数据库中但由于某种原因,如果itemid = 0,我无法插入?下面的代码,如果我这样做又增加了8行?:
for ($i = 0; $i < count($values); $i++)
{
$item = $values['item'][$i];
$description = $values['description'][$i];
$rate = $values['rate'][$i];
$itemid = $values['itemid'][$i];
if($itemid)
{
// Update item
$query = "UPDATE `invoice_items`...";
}
else
{
// Add new item
$query = "INSERT INTO `invoice_items`...';
}
}
#
更新
#这是我现在拥有的,但是当我只更新项目时,我仍在向数据库中插入另外7个项目:
foreach ($outArray as $row)
{
$item = $row['item'];
$description = $row['description'];
$rate = $row['rate'];
$qty = $row['qty'];
$price = $row['price'];
$itemid = $row['itemid'];
if($row['itemid'] >= 1)
{
$query = "UPDATE `invoice_items` SET `item` = '?', `description` = '?', `rate` = '?', `qty` = '?', `price` = '?' WHERE `id` = '?' LIMIT 1;";
$query_prepare = $this->prep_q($query,array($item,$description,$rate,$qty,$price,$itemid));
}
else
{
$query = "INSERT INTO `invoice_items` (`item`,`invoice_id`,`description`,`rate`,`qty`,`price`) VALUES ('?','?','?','?','?','?') LIMIT 1;";
$query_prepare = $this->prep_q($query,array($item,$invoice_id,$description,$rate,$qty,$price));
}
$this->setquery($query_prepare);
}
答案 0 :(得分:0)
此外,您应该创建一个可行的数组,每一行都有自己的名称,描述,比率,itemid。
所以代替:
Array
(
[item] => Array
(
[0] => item listing 1
[1] => item listing 2
)
[description] => Array
(
[0] => item testing description
[1] => item testing description
)
[rate] => Array
(
[0] => 1.00
[1] => 2.00
)
[itemid] => Array
(
[0] => 1
[1] => 2
)
)
您的数组应如下所示:
Array
(
[0] => Array
(
[item] => item listing 1
[description] => item testing description
[rate] => 1.00
[itemid] => 1
)
[1] => Array
(
[item] => item listing 2
[description] => item testing description
[rate] => 2.00
[itemid] => 2
)
然后你可以简单地使用foreach, PDO或mysqli :
$sql['update'] = "UPDATE `invoice_items`
SET `item` = :item, `description` = :description, `rate` = :rate
WHERE `itemid` = :itemid";
$sql['insert'] = "INSERT INTO `invoice_items` (itemid,item,description,rate)
VALUES (:itemid, :item, :description,:rate)";
foreach ($array as $row){
if($row['itemid'] >= 1){
$stmt = $db->prepare($sql['update']);
}else{
$stmt = $db->prepare($sql['insert']);
}
$stmt->execute($row);
}