检查数据库中的条目是否存在 - Drupal 7

时间:2015-03-12 13:09:10

标签: php mysql database drupal drupal-7

我创建了一个模块,当cron运行时,它从监视程序表中获取wid,变量和时间戳,并将其传递给新表blablabla。我想如果blablabla表中存在具有相同变量的值,则不传递此值。按照我的代码:

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

1 个答案:

答案 0 :(得分:1)

如果存在符合条件的行,则需要查询表以查看数据是否存在,然后不执行任何操作。例如;

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

鉴于您在问题中缺少blablabla_table()函数,我很难给出一个例子,我认为它写入了blablabla_table。将来在没有占位符名称的情况下提出问题。