How can I use my passed-in $events array in a DELETE WHERE IN query in CodeIgniter?
public function remove_events(array $events): void
{
$sql = "DELETE FROM events WHERE event_id IN $events";
$query = $this->db->query($sql);
}
How can I use my passed-in $events array in a DELETE WHERE IN query in CodeIgniter?
public function remove_events(array $events): void
{
$sql = "DELETE FROM events WHERE event_id IN $events";
$query = $this->db->query($sql);
}
if $event is a single value then you must use
$sql = "delete from events where event_id = $events";
Or if it is an array
$sql = "delete from events where event_id in (".implode(',', $events).") ";
Let Active Record make the job:
$this->db->where_in('id', $events)->delete('events');
All values are escaped automatically producing safer queries.
Do NOT implode your array into a comma-separated string -- this will provide no protections and will not work as intended if any of the values contain the glue string used in the implosion.
With a raw SQL string, CodeIgniter expects only a ? after IN and it will automatically wrap the placeholder in parentheses (do not add the parentheses yourself because it will break the script/query). The second parameter of the query() method accepts an array of parameters. In your case, the first item in that 2nd parameter needs to be your array. Notice that your array is nested in this containing array.
public function removeEvents(array $eventIds): void
{
$sql = "DELETE FROM events WHERE event_id IN ?";
$query = $this->db->query($sql, [$eventIds]);
}
Alternatively, you can enjoy active record syntax which is more elegant but restricts your ability to directly copy your codebase SQL into your preferred RDBMS for testing/development.
public function removeEvents(array $eventIds): void
{
$this->db->where_in('event_id', $eventIds)->delete('events');
}