Monday 20 July 2015

Deleting Data in Codeigniter



$this->db->delete();

Generates a delete SQL string and runs the query.

$this->db->delete('tablename', array('id' => $id));

// Produces:
// DELETE FROM tablename
// WHERE id = $id
 
The first parameter is the table name, the second is the where clause. You can also use the where() or or_where() functions instead of passing the data to the second parameter of the function:

$this->db->where('id', $id);
$this->db->delete('tablename');

// Produces:
// DELETE FROM tablename
// WHERE id = $id

An array of table names can be passed into delete() if you would like to delete data from more than 1 table.

$tables = array('table1', 'table2', 'table3');
$this->db->where('id', '5');
$this->db->delete($tables);

If you want to delete all data from a table, you can use the truncate() function, or empty_table().

$this->db->empty_table();

Generates a delete SQL string and runs the query. $this->db->empty_table('tablename');

// Produces
// DELETE FROM tablename

$this->db->truncate();

Generates a truncate SQL string and runs the query.

$this->db->from('tablename');
$this->db->truncate();
// or
$this->db->truncate('tablename');

// Produce:
// TRUNCATE tablename

No comments:

Post a Comment