The code I wrote that uses db_insert()
and db_merge()
works great. I can populate the database table well (also using a post http). Now I want to get a success/fail message.
How do I show a message after executing a query?
The code I wrote that uses db_insert()
and db_merge()
works great. I can populate the database table well (also using a post http). Now I want to get a success/fail message.
How do I show a message after executing a query?
You show messages using drupal_set_message()
:
Sets a message to display to the user.
Messages are stored in a session variable and displayed in page.tpl.php via the $messages theme variable.
You can use drupal_set_message() to display a message in the browser, this can be marked as a status', 'warning' or 'error' message.
If you want to debug your code, the Devel module is recommended and provides the dpm() function. Besides being able to print a simple message, dpm()
also allows to display an array or object quite easy.
If you want to know the status of the insert, perhaps a more suitable function for your use case is drupal_write_record
Return value
If the record insert or update failed, returns FALSE. If it succeeded, returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
To update a record, you need to have the 'primary key field name' => 'value'
in the $record
(2nd) parameter passed to the function. As well as that, you need to pass the $primary_keys
(3rd) parameter which is a simple array of your primary key field names without the values. If it's just a single primary key (id
for example), then you can pass it as a string as well.
If you omit the 3rd parameter $primary_keys
then it's going to perform a db_insert
otherwise it does a db_update
.
In fact, as you follow the function along, it shows you exactly how to evaluate whether the db_insert
or db_update
were a success or not. So I won't be covering it here.
by the way I've solved my problem by try catch as @clive adviced me on comment,
Thedrupal_write_record
works as well so thank you Beebee
If it can helps, here is the part of code with the try catch :
try{
$uid_courant = db_query("SELECT (MAX(uid))+1 as max_id FROM {users}")->fetchCol();
$create_user = db_merge('users')
->key(array('name'=> $data["username_client"],'uid'=>'uid'))
->fields(array(
'uid'=> $uid_courant,
'name'=>$data["username_client"],
'pass'=>$data['password_cl'],
'mail'=>$data["mail_cl"],
'created'=>time()
))
->execute();
}
catch(Exception $e){
$user_existe = array('code'=>'1','error'=>'1');
}
Here the code insert a new user only if there's no user with same username on table "users", if not it returns an error. and in the same time i'm inserting the same user on anotre custom table i've created this table is called "client" and do same verifications.
Thank you all.