Updating a table
Updating a value or a group of values in a table is very easy using the DBAPI update function.
The function:
function update($fields, $table, $where="") {
if(!$table) return false;
else {
if(!is_array($fields)) $flds = $fields; // if single value is passed
else {
foreach($fields as $key=>$value) {
if($flds) $flds .=","; // add commas between fields
$flds .= $key."="; // field =
$flds .= "'".$value."'"; // 'value'
}
}
$where = ($where != "") ? "WHERE $where" : "";
return $this->query("UPDATE $table SET $flds $where;");
}
}
To use
$rows_affected = $modx->db->update("fields", "table_name" [, "where value"]);
The "fields" argument
The "fields" argument can be an (associative) array if more than one field is to be updated. ie:
$fields = array(
"field1" => 1,
"field2" => 2,
"field3" => "three"
)
$rows_affected = $modx->db->update($fields, "table_name", "where value");
Otherwise, it can simply be the field and value you want to update:
$rows_affected = $modx->db->update("field=value" "table_name", "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_name = $modx->getFullTableName("table");
$rows_affected = $modx->db->update($fields, $table_name, "where value");
The "where" argument
The "where" argument tells the database the specific record to update:
$rows_affected = $modx->db->update($fields, "table_name", "field = value");
Examples
Example 1
$table = $modx->getFullTableName("site_content");
$fields = array(
"pagetitle" => "New Title",
"alias" => "new-alias",
"menuindex" => 2,
"published" => 1
)
$rows_affected = $modx->db->update($fields, $table, "id = 45");
will change document 45's title to "New Title", its alias to "new-alias", make it the second item in the menu, and publish it.
Example 2
$table = $modx->getFullTableName("system_settings");
$rows_affected = $modx->db->update("setting_value = '5'", $table, "setting_name='default_template'");
will change the site's default template to template 5.