0

I created a custom module where I am querying the database, for example with code similar to the following one.

$query = db_select('node', 'n');
$query->fields('n', array('nid'));
$nid = $query->execute()->fetchField();

I want to print the warning, error, and success messages after the execution of the query. How can I achieve this?

2
  • It depends what you mean by "error" and "success". Is an "error" based on the query not returning a certain record? A certain number of records? Or do you want to catch SQL syntax/logic errors?
    – Clive
    Commented Mar 9, 2018 at 10:15
  • @Clive.. want to catch SQL syntax/logic errors
    – user82343
    Commented Mar 9, 2018 at 10:41

2 Answers 2

2

Try to follow below code..

   try {
        $query = db_select('node', 'n');
        $query->fields('n', array('nid'));
        $nid = $query->execute()->fetchField();
        drupal_set_message(t('Print your sucess message here'));
      }
    catch(Exception $e){
        drupal_set_message(t('Print your error message here'),'error');
    }
2
  • Please stop signing your answers off with “Thank you”, it’s not necessary. Er, thanks!
    – Clive
    Commented Mar 13, 2018 at 10:10
  • but where is the SQL syntax/logic error message we want to fetch and display? It is supposed to come from the mysql server, not an arbitrary "(y)our error message" invented by us....
    – Max
    Commented Aug 22 at 23:22
1

You can display drupal messages using the pre-defined function drupal_set_message().

For example:

$query = db_select('node', 'n');
$nid = $query->fields('n', array('nid'));
$nid = $nid->execute()->fetchField();
if(!empty($nid)){
     //Do something
     drupal_set_message(t('Your success message'), $type = 'status');
}else{
    //Do something
     drupal_set_message(t('Your error message'), $type = 'error');
}

For more information about messages, click here

3
  • 1
    @usmanjutt84..Thank you.. I updated the question now
    – user82343
    Commented Mar 9, 2018 at 9:44
  • @blue-moon, see I hope it'll helps Commented Mar 9, 2018 at 10:14
  • If I understand correctly, OP clarified that they want to get the MySQL error message (e.g., syntax error in SQL command).
    – Max
    Commented Aug 22 at 23:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.