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?

  • 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 Mar 9 '18 at 10:15
  • @Clive.. want to catch SQL syntax/logic errors – user82343 Mar 9 '18 at 10:41
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');
    }
  • Please stop signing your answers off with “Thank you”, it’s not necessary. Er, thanks! – Clive Mar 13 '18 at 10:10
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

  • 1
    @usmanjutt84..Thank you.. I updated the question now – user82343 Mar 9 '18 at 9:44
  • @blue-moon, see I hope it'll helps – usmanjutt84 Mar 9 '18 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy