2

When I try this code:

$query = '';
foreach ($data as $row)
{
    $where = array(
        'community_id' => $row->id,
        'user_id' => $this->session->user_id,
        'status' => 'invited_to_join',
    );
    $update = array(
        'status' => 'joined',
    );
    $query .= $this->db->set($update)->where($where)->get_compiled_update('community_members') . '; ';
}
if ($query)
{   
    return $this->db->query($query);
}

it gives me the error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE `community_members` SET `status` = 'joined' WHERE `community_id` = '18' A' at line 4

this answer uses a straightforward query with CASE, but I don't know how to convert that into CodeIgniter's query builder.

3 Answers 3

5

You can direct use array $data['id'] like this, but you will need to make looped UPDATE queries to access each $data['id'] value.

$this->db->set('status','joined');
$this->db->where('community_id',$data['id']);
$this->db->where('user_id',$this->session->user_id); 
$this->db->where('status','invited_to_join');
$this->db->update('community_members');
Sign up to request clarification or add additional context in comments.

Comments

2

You can also use where clause this way:

    $where = "'community_id'=".$data['id']." AND user_id=".$this->session-user_id." AND status='invited_to_join'";

    $this->db->set('status','joined');
    $this->db->where($where);
    $this->db->update('community_members');

Thank You!!!

2 Comments

I think your first answer was much better. this method requires manual string escaping..
This unexplained script does not enjoy the protections of CodeIgniter's auto-quoting/escaping of WHERE clause conditions.
0

The only reason to iterate anything is to accumulate the community ids from the 2d $data array. Use array_column() to isolate the ids, then pass them into a where_in() call. Chain the update() call which includes the SET clause and the remaining WHERE clause conditions. This cleanly and safely executes the query in a single trip to the database.

$update = $this->db
    ->where_in('community_id', array_column($data, 'id'))
    ->update(
        'community_members',
        ['status' => 'joined'],
        [
            'status' => 'invited_to_join',
            'user_id' => $this->session->user_id,
        ]
    );
return $update ? $this->db->affected_rows() : 0;

As a general rule, I advise against directly accessing submission or session data directly in model methods. Writing simple unit tests and maximizing method utility is achieved by passing in all dynamic data from call sites.

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.