0

我在这里回答了我的第一个问题: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);
}
4

1 回答 1

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);
}
于 2012-07-19T06:43:30.220 回答