Deleting a row from a table, or even all the rows in a table, is very easy using the DBAPI delete function.

The function:

function delete($from, $where = "") {
  if(!$from) return false;
  else {
    $table = $from;
    $where = ($where != "") ? "WHERE $where" : "";
    return $this->query("DELETE FROM $table $where;");
  }
}

To use

$rows_affected = $modx->db->delete("table"[, "where value"]);

The "table" argument

The "table" argument is the table to update. You can use the MODx function to return the full tablename; this is probably the best way, since you won't have to remember to include the prefix of the table names for your site:

$table = $modx->getFullTableName("table");
$rows_affected = $modx->db->delete($table[, "where value"]);

The "where" argument

To optionally specify the specific record to delete, include the field and value to use in a WHERE clause:

$table = $modx->getFullTableName("table");
$rows_affected = $modx->db->delete($table, "field = value");

Example

$table = $modx->getFullTableName("site_templates");
$rows_affected = $modx->db->delete($table, "id = 5");

will delete the template with ID 5.

Note

Using this function without specifying a "where" value will delete all the rows in the table. For a number of reasons it would be better to use a "TRUNCATE" query to empty a table.

$table = $modx->getFullTableName("table_name");
$sql = "TRUNCATE [TABLE] $table";
$modx->db->query($sql);

MySQL documentation reference


( back to top )