delete

API Quick reference
Variable name: delete
CMS versions: 0.9.x + Evo
Input parameters: (string $from [, string $where [, string $fields]])
Return if successful: true
Return type: bool
Return on failure: false
Object parent:

API:DB:delete

Description

bool delete(string $from [, string $where [, string $fields]])

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

This function attempts to delete from the mysql table with the given paramaters. If no $where is given, this function will delete all the rows in the table $from. $where is the full string of a mysql where clause (eg: $where = "id=4 AND status='active'"). $fields denotes the specific fields to be deleted, leave blank to delete the whole row.

Function returns true on success, and false on failure.

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

The "table" argument
The "table" argument is the table to update. You can use the Evo 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");

Usage / Examples

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

will delete the template with ID 5.

function login($username, $password)
{
global $modx, $table_prefix;
$username = $modx->db->escape($username);
$password = $modx->db->escape($password);

$res = $modx->db->select("id", $table_prefix.".modx_web_users", 
"username='$username' AND password='".md5($password)."'");
if($modx->db->getRecordCount($res))
{
$_SESSION['userid'] = $id;
//other log in things...
}
else
{
//incorrect login
}
}

Example2:

//delete a user of id $id
global $modx, $table_prefix;
$id = $modx->db->escape($id);
$modx->db->delete($table_prefix.".modx_web_users", "id = $id");

Related

Notes

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);

As with all mysql calls, care must be taken to sanitize the variables passed. One should use $s = $modx->db->escape($s) before passing to any of these functions.

Function Source

File: manager/includes/extenders/dbapi.mysql.class.inc.php
Line: 155

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

Suggest an edit to this page.