1

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.

2 Answers 2

6

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

kumar_v, Thanks for solution.I would like to implement transaction here. How is it possible??
1
$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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.