2

I have two values(bookingId) in index array and now i want to update query using these values but right now unable break array in loop, I want to run update query (according to count values in array) Here is my code,Where i am wrong ?

$bookingIds; // contaning two values 176,190
$counts = count($bookingIds);  // counting array values
for ($x = 1; $x <= $counts; $x++) 
    {
        $data = array('approved' => "1");
        $this->db->where('bookingId', $bookingIds);
        $this->db->update('notifications', $data);
    }

3 Answers 3

2

I think you should mention an index for your array while looping.And your $x must start with 0

$bookingIds; // contaning two values 176,190
$counts = count($bookingIds);  // counting array values
for ($x = 0; $x < $counts; $x++) 
    {
        $data = array('approved' => "1");
        $this->db->where('bookingId', $bookingIds[$x]);
        $this->db->update('notifications', $data);
    }
Sign up to request clarification or add additional context in comments.

5 Comments

I thought you were more correct when you suggested using Base 0 for the index and the array.
@GetSet i thought it too but then i looked at the condition btw can you help me if i'm wrong?
You're likely right. $bookingIds would most probably already be Base 0 since OP relies on count() which would be the Base 1 total of that.
Thanks @GetSet now i have changed the condition so that it is better for OP to understand as well thanks for your reply though 😊
No prob. I just hope OP realizes or understands that in going to Base 0, the <= would be a logical error.
1

One refactoring of the above using foreach to remove the whole indexing issue would be

$data = array('approved' => "1");
foreach ($bookingsIds as $bookingId )
{
    $this->db->where('bookingId', $bookingId);
    $this->db->update('notifications', $data);
}

Comments

0

Looks like you are using a framework; if it provides a whereIn() method, it would be more efficient to use it (runs less SQL queries):

$data = ['approved' => '1'];
$this->db
    ->whereIn('bookingId', $bookingIds)
    ->update('notifications', $data);


(Just be aware you can't put thousands and thousands of values in such a "where in" clause, because the query would be huge. Personally I process this kind of stuff in chunks, like 500 records per query.)

(Also, make sure no error happens if the "where in" array (here, $bookingIds) is empty. It's a special case, that the framework has to handle properly.)

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.