简体   繁体   中英

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM