Home » Php » php – Codeigniter – How to delete a row from a table but only once?

php – Codeigniter – How to delete a row from a table but only once?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m currently building an events management site using Codeigniter.
Each user can ‘purchase’ tickets to an event and then view a list of
all their events that they’ve got tickets for. I want to give the user
an option to remove an event from their list and refund one ticket.
I’ve got it mostly working with the following function;

public function remove_user_event($event_id)
{
    $this->db->where('event_id', $event_id);
    $this->db->where('user_id', $this->session->userdata('user_id'));
    $this->db->delete('purchased_tickets');
    return true;
}

It does remove the event correctly for the user but the only problem is that it removes every occurrence of this event rather than just doing it the one time. i.e. if they’ve ‘purchased’ 3 tickets when attempting to remove one it instead removes all 3. Just wondering how I can only remove the event once per time the function is called.
Any help would be appreciated, cheers.

How to&Answers:

If you want to limit the number of rows to be deleted, you use the LIMIT clause as follows:

public function remove_user_event($event_id)
{
   $this->db->where('event_id', $event_id);
   $this->db->where('user_id', $this->session->userdata('user_id'));
   $this->db->limit(1); 
   $this->db->delete('purchased_tickets');
   return true;
}