mysql - 使用限制时使用 Drupal 7 数据库 API 获取总行数

标签 mysql database api drupal drupal-7

我正在使用 Drupal 7 数据库 API 来搜索我的表。我还使用分页和排序扩展器。所以问题是,当我的查询由于分页而使用限制时,如何显示找到的记录总数?我是否需要运行包含所有条件两次的查询?一次是为了计数,另一次是有限制的?这看起来效率很低。这是我的代码供引用。我是数据库 API 的新手,所以如果我做错了什么,请随意调整我的代码或为我指出正确的方向。另外,我还没有完成这个任务,只有一个条件,但我最终会得到 3 个条件。谢谢:

function job_search() {
  // Initialising output
  $output = 'SOME STUFF';

  // Table header
  $header = array(
    array('data' => 'Description'),
    array('data' => 'Location', 'field' => 'job_location_display'),
    array('data' => 'Specialty', 'field' => 'specialty_description'),
    array('data' => 'Job Type', 'field' => 'job_board_type'),
    array('data' => 'Job Number', 'field' => 'job_number'),
  );

  // Setting the sort conditions
  if(isset($_GET['sort']) && isset($_GET['order'])) {
    // Sort it Ascending or Descending?
    if($_GET['sort'] == 'asc')
      $sort = 'ASC';
    else
      $sort = 'DESC';

    // Which column will be sorted
    switch($_GET['order']) {
      case 'Location':
        $order = 'job_location_display';
        break;
      case 'Specialty':
        $order = 'specialty_description';
        break;
      case 'Job Number':
        $order = 'job_number';
        break;
      case 'Job Type':
        $order = 'job_board_type';
        break;
      default:
        $order = 'job_number';
    }
  }
  else {
    $sort = 'ASC';
    $order = 'job_number';
  }

  // Query object
  $query = db_select("jobs", "j");  

  // Adding fields
  $query->fields('j');

  if(isset($_GET['location'])) {
    $query->condition('j.job_state_code', $_GET['location'], '='); 
  }

  // Set order by
  $query->orderBy($order, $sort);  

  // Pagination
  $query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);

  // Executing query
  $result = $query->execute();

  // Looping for filling the table rows
  while($data = $result->fetchObject()) {
    $description = '<div class="thumbnail"><img src="/sites/all/themes/zen/vista_assets/images/job_headers/' . $data->job_image_file . '"/></div>';
    $description .= '<div class="title">' . $data->job_board_subtitle . '</div>';
    // Adding the rows
    $rows[] = array($description, $data->job_location_display, $data->specialty_description, $data->job_board_type, $data->job_number);    
  }

  $output .= theme('pager');

  // Setting the output of the field
  $output .= theme_table(
    array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array('id' => array('job-listing')),
      'sticky' => true,
      'caption' => '',
      'colgroups' => array(),
      'empty' => t("No records found.")
    )
  ).theme('pager');

  // Returning the output
  return $output;
}

最终成功了:

//get total records
$num_rows = $query->countQuery()->execute()->fetchField(); 

// add paging and sorting
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(20);

//execute again
$result = $query->execute();

最佳答案

根据文档:https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7

为了获取总行数,最好使用db_query()函数,因为它具有返回查询总数的方法rowCount()行:

<?php
// Using the same query from above...
$uid = 1;
$result = db_query('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));

// Fetch next row as a stdClass object.
$record = $result->fetchObject(); 

// Fetch next row as an associative array.
$record = $result->fetchAssoc();

// Fetch data from specific column from next row
// Defaults to first column if not specified as argument
$data = $result->fetchColumn(1); // Grabs the title from the next row

// Retrieve all records into an indexed array of stdClass objects.
$result->fetchAll();

// Retrieve all records as stdObjects into an associative array
// keyed by the field in the result specified.
// (in this example, the title of the node)
$result->fetchAllAssoc('title');

// Retrieve a 2-column result set as an associative array of field 1 => field 2.
$result->fetchAllKeyed();
// Also good to note that you can specify which two fields to use
// by specifying the column numbers for each field
$result->fetchAllKeyed(0,2); // would be nid => created
$result->fetchAllKeyed(1,0); // would be title => nid

// Retrieve a 1-column result set as one single array.
$result->fetchCol();
// Column number can be specified otherwise defaults to first column
$result->fetchCol($db_column_number);

// Count the number of rows
$result->rowCount();
?>

关于mysql - 使用限制时使用 Drupal 7 数据库 API 获取总行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19526612/

相关文章:

mysql - 如何左连接 2 个字段匹配的 2 个表

php - 创建 php 数据库并显示其内容

c# - discord 添加 SetGame/SetStatus

php - MySQL PDO UNION 查询,查找结果来自的表

json - 从R将数据导入Elastic Search

xml - 如何在mac中制作xml文件?

MYSQL - MAX() 返回错误的日期

php - GROUP BY mysql 只显示一行。但也想要重复

java - 在jsp中将编辑按钮保存在相同的表单上

php - 从数据库加载 jreviews 字段