[Drupal] What is the usage of drupal_write_record function in Drupal 7?
The drupal_write_record function is used to insert or update a record in the database based on the schema of the table. It helps in executing less database query. Let's take a look at the function given below.
drupal_write_record($table_name, &$record, $primary_keys = array());
- $table_name : This variable determines the table name that is defined in the hook_schema().
- $record : This is an object or array representing the record to insert or update, and is passed in by reference.
- $primary_keys : This variable denotes the primary key of the table and is optional. If this argument is omitted, indicate it by inserting a new record to the table. For updating a table, this argument specifies the Primary key of the table. For single primary key, we can pass the variable as string. Otherwise, we can pass it as an array().
We offer offshore drupal development services to know more, get in touch with us.
Here's a simple example. For creating a new record, we can use the following code,
$table_name = 'my_table'; $data->column_name_1 = value_1; $data->column_name_1 = value_2; $data->column_name_1 = value_3; drupal_write_record($table_name, $data);
For updating an existing record,
$table_name = 'my_table'; $data->column_id = column_id; $data->column_name_1 = value_2; $data->column_name_1 = value_3; drupal_write_record($db_name, $data, 'column_id');
The function returns false, if the record insert or update operation has failed. Otherwise, the function returns 1 for insert or 2 for the update. I believe that this topic has proved informative for you. For more details, please feel free to contact us.