0
votes

I'm trying to update a column in the MySQL table by using CodeIgniter's "update" active record. However, I can only update the first row of the array I put in. What am I doing wrong?

Code:

       $invalid_email_raw='[email protected];
                           [email protected];
                           [email protected];
                           [email protected]';

       $invalid_email=explode(';', $invalid_email_raw);

       foreach ($invalid_email as $email):

            $data=array(
                'status'=>'unsubscribed'
                );

            $this->db->where('email', $email);
            $this->db->update('user', $data);

        endforeach;

Essentially, the code breaks the 4 emails into an array, and uses foreach to update the corresponding status where the email is found.

However, only the status for "[email protected]" is updated. All the other 3 are unchanged.

What am I doing wrong?

3
Why don't you do a single query instead? - Shomz
not sure how to do that...mind showing an example? - user3192948
In a single query you can do it with batch update $this->db->update_batch(); - machineaddict
thanks but due to my limited skill I still can't figure out the exact way. An answer with this approach to my question is much appreciated! - user3192948
See Parag Tyagi answer below. This is how you do it. It also executes faster. - machineaddict

3 Answers

1
votes

You are using newlines, which after explode you have:

[email protected]
\[email protected]
\[email protected]
\[email protected]

\n being new line. So, in that update matches only the first email.

0
votes

Because your update query in loop and if each time condition satisfy so it update the status of all four.

0
votes

Use update_batch(), also trim your array values using array_map(). Try below code,

$invalid_email_raw = '[email protected];
                       [email protected];
                       [email protected];
                       [email protected]';

$invalid_email = array_map('trim', explode(';', $invalid_email_raw));

$data = array();
foreach($invalid_email as $email)
{
    $data[] = array(
                  "email" => $email,
                  "status" => "unsubscribed"
               );
}

if(!empty($data))
{
    $this->db->update_batch('user', $data, 'email');
}