duannv2081
duannv2081
2014-01-13 07:52
浏览 26
已采纳

使用循环插入多行时获取成功确认

How can I get success confirmation while I am using loop to insert table rows in MySql database table?

My code is like below (I am using CodeIgniter):

foreach($bookids as $key=>$bookid)
{
    $this->db->query("INSERT INTO `book` (`invoice_id`,`item_id`,`quantity`,`price`) VALUES (`$invoice_id`,`$product_id`,`$product_quantitys[$key]`,`$product_prices[$key]`)");        
}

I would like to get confirmation after all rows inserted successfully.

图片转代码服务由CSDN问答提供 功能建议

当我使用循环在MySql数据库表中插入表行时,如何获得成功确认?

我的代码如下(我正在使用 CodeIgniter ):

  foreach($ bookids as $ key =>  $ bookid)
 {
 $ this-> db-> query(“INSERT INTO`book`(`invoice_id`,`item_id`,`quantity`,`price`)VALUES(`$ invoice_id`,`  $ product_id`,`$ product_quantitys [$键]`,`$ product_prices [$键]`)“);  
} 
   
 
 

我希望在所有行成功插入后得到确认。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dslf46995
    dslf46995 2014-01-13 08:03
    已采纳

    You can use affected_rows() function to check data inserted( or updated) or not.

    $actual_count = count($bookids); // array of book ids
    $inserted_count = 0;
    
    foreach($bookids as $key=>$bookid)
    {
        $this->db->query("INSERT INTO `book` (`invoice_id`,`item_id`,`quantity`,`price`) VALUES (`$invoice_id`,`$product_id`,`$product_quantitys[$key]`,`$product_prices[$key]`)");        
        if($this->db->affected_rows()>0) // data inserted, so it will return 1
        {
          $inserted_count ++;
        }
    }
    
    if($actual_count  == $inserted_count )
    {
      //throws success message to controller
    }
    else
    {
       // throws error message with mismatch record count
    }
    
    点赞 评论
  • dtcpvz8162
    dtcpvz8162 2014-01-13 08:08
    $success = true;    
    
    foreach($bookids as $key=>$bookid)
    {
        if ($this->db->query("INSERT INTO `book` (`invoice_id`,`item_id`,`quantity`,`price`) VALUES         (`$invoice_id`,`$product_id`,`$product_quantitys[$key]`,`$product_prices[$key]`)"))
        {} else { $success = false}
    }
    
    if ($success){
       code on success...
    }
    

    Explanation: SImply if your query success do nothing, if one of queries will fail flag $success will be false and you will know that something went wrong

    点赞 评论

相关推荐