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.
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
}
$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