db_insert_if_ok(), insert_if_ok(), db_update_if_ok(), update_if_ok(), change_if_ok() form()
After a valid POST, insert or update a DB row from the validated fields, then show a notice and redirect.
form()->db_insert_if_ok($table, $fields, $add_fields = [], $extra = [])
form()->insert_if_ok($table, $fields, $add_fields = [], $extra = [])
form()->db_update_if_ok($table, $fields, $where_id = null, $extra = [])
form()->update_if_ok($table, $fields, $where_id = null, $extra = [])
form()->change_if_ok($table, $fields, $type, $extra = [])Options
| Option | Meaning |
|---|---|
$table, $fields | Table name; fields to write: ['login', 'email'] or ['form_name' => 'db_column']. |
$add_fields | db_insert_if_ok(): extra column => value pairs (not validated), e.g. add_date. |
$where_id | db_update_if_ok(): id of the row; default $replace['id'] (or the form option id key). |
$type | change_if_ok(): insert or update. |
on_before_update, on_after_update, on_success_text | Callbacks and the notice text. |
redirect_link, no_redirect, force | Where to go after saving (default this page); stay; write without validation. |
Example
Code
// the docs site writes nothing: CONF_NO_DB_WRITES, on for every example here, validates and reports instead of writing
$row = ['id' => 7, 'title' => 'Spring sale'];
return form($row)
->validate(['title' => 'trim|required'])
->db_update_if_ok('static_pages', ['title'], null, ['no_redirect' => 1])
->text('title')
->save()
->db_insert_if_ok('static_pages', ['title'], ['add_date' => time()], ['no_redirect' => 1])
->insert_if_ok('static_pages', ['title'], [], ['no_redirect' => 1])
->update_if_ok('static_pages', ['title'], 7, ['no_redirect' => 1])
->change_if_ok('static_pages', ['title'], 'update', ['no_redirect' => 1]);Notes
insert_if_ok()/update_if_ok()are aliases; one form keeps one write (the last call wins), so the example sets it five times and onlychange_if_ok()stays.- Writes use
insert_safe()/update_safe()(values escaped) and invalidate the table cache. $PROJECT_CONF['form2']['CONF_NO_DB_WRITES'] = truevalidates and runs the callbacks but writes nothing (demo sites; the docs examples run with it).- The fields must be the validated ones: list them explicitly, never write
$_POSTas it is.
See also: form/validate, form/events