Search code examples
phpmysqldatabasedrupaldrupal-7

Check if the entry in DB exists - Drupal 7


I have made a module that when cron run it gets the wid and variables and timestamp from the watchdog table and pass it in a new table blablabla. I want if a value with same variables exists in the blablabla table do not pass this value. Here follow my code:

function blablabla_cron() {

  // Begin building the query.
  $query = db_select('watchdog', 'th')
    ->extend('PagerDefault')
    ->orderBy('wid')
    ->fields('th', array('wid', 'timestamp'))
    ->limit(2000);

  // Fetch the result set.
  $result = $query -> execute();

  // Loop through each item and add to $row.
  foreach ($result as $row) {
    blablabla_table($row);
  }
}

function error_log_jira_table($row) {

  $timestamp = $row -> timestamp;
  $wid = $row -> wid;
  $variables = $row -> variables;

  $nid = db_insert('error_log_jira')
    ->fields(array(
      'timestamp' => $timestamp,
      'wid' => $wid,
      'variables' => $variables
    ))
    ->execute();
}

Solution

  • You need to query the table to see if the data exists before writing to it, if a row exists matching the criteria then do nothing. For example;

    function blablabla_cron() {
    
      // Begin building the query.
      $query = db_select('watchdog', 'th')
        ->extend('PagerDefault')
        ->orderBy('wid')
        ->fields('th', array('wid', 'timestamp', 'variables'))
        ->limit(2000);
    
      // Fetch the result set.
      $result = $query -> execute();
    
      // Loop through each item and add to $row.
      foreach ($result as $row) {
    
        // Query Blablabla table for row matching timestamp and variables
        $r = db_select('blablabla', 'b')
          ->fields('b')
          ->condition('timestamp', $row->timestamp, '=')
          ->condition('variables', $row->variables, '=')
          ->execute();
    
        // If row doesn't exist then create it (I assume blablabla_table creates?)
        if($r->rowCount() == 0) {
          blablabla_table($row);
        }       
      }
    }
    

    Pretty difficult to give an example given that you're missing the blablabla_table() function in your question, I assume it writes to the blablabla_table. In the future ask questions without placeholder names.