db_query_range

Хочешь помочь с переводом? Это очень просто и быстро. Лишь зарегистрируйся, и можешь тут же начать переводить.

includes/database.mysql.inc, строка 228

Версии
5 – 6
db_query_range($query)

Выполняет ограниченный диапазоном запрос к активной базе данных.

Используйте эту функцию как заменитель db_query(), когда необходимо получить лишь часть выборки запроса. Пользовательские аргументы к SQL-запросу должны передаваться отдельными параметрами к функции, чтобы быть правильно экранированными, дабы избежать SQL-инъекций.

Примечание: использование этого синтаксиса приведет к тому, что NULL и FALSE будут превращаться в десятичный 0, а TRUE в десятичную 1.

Параметры

$query Строка, содержащая SQL-запрос.

... Переменное количество аргументов, которые подставляются в запрос по типу printf(). Вместо переменного количества аргументов, можно использовать один массив, содержащий необходимые аргументы. Правильные шаблоны для подстановки: '%s', '%d', '%f', '%b' (двоичные данные, не следует помещать в кавычки '') и '%%'.

$from Номер первого ряда в выборке.

$count Максимальное количество рядов, которое следует возвратить.

Возвращаемое значение

Результирующий ресурс запроса или FALSE, если запрос вызвал ошибку.

Связанные темы

▾ 40 функции вызывают db_query_range()

aggregator_block in modules/aggregator/aggregator.module
Реализация hook_block().
aggregator_page_categories in modules/aggregator/aggregator.pages.inc
Коллбэк меню; показывает все категории, используемые аггрегатором.
aggregator_page_rss in modules/aggregator/aggregator.pages.inc
Коллбэк меню. Генерирует фид из материалов аггергатора или категорий в формате RSS 0.92.
aggregator_page_sources in modules/aggregator/aggregator.pages.inc
Коллбэк меню; показывает все фиды, используемые аггрегатором.
batch_example_batch_1 in developer/examples/batch_example.module
Batch 1 : Load 100 times the node with the lowest nid
batch_example_op_2 in developer/examples/batch_example.module
Batch operation for batch 2 : load all nodes, 5 by five This is a multipart operation, using the
blogapi_blogger_get_recent_posts in modules/blogapi/blogapi.module
Blogging API callback. Returns the latest few postings in a user's blog. $bodies TRUE <a href='http://movabletype.org/docs/mtmanual_programmatic.html#item_mt%2EgetRecentPostTitles'> returns a bandwidth-friendly list</a>.
blog_block in modules/blog/blog.module
Реализация hook_block().
blog_feed_last in modules/blog/blog.pages.inc
Menu callback; displays an RSS feed containing recent blog entries of all users.
blog_feed_user in modules/blog/blog.pages.inc
Menu callback; displays an RSS feed containing recent blog entries of a given user.
book_update_6000 in modules/book/book.install
Drupal 5.x to 6.x update.
comment_get_recent in modules/comment/comment.module
Find a number of recent comments. This is done in two steps. 1. Find the n (specified by $number) nodes that have the most recent comments. This is done by querying node_comment_statistics which has an index on last_comment_timestamp, and is thus a...
do_search in modules/search/search.module
Do a query on the full-text search index for a word or words.
drupal_is_denied in includes/bootstrap.inc
Perform an access check for a given mask and rule type. Rules are usually created via admin/user/rules page.
forum_block in modules/forum/forum.module
Реализация hook_block().
forum_get_forums in modules/forum/forum.module
Returns a list of all forums for a given taxonomy id
forum_nodeapi in modules/forum/forum.module
Implementation of hook_nodeapi().
hook_update_index in developer/hooks/core.php
Обновляет полнотекстовый индекс Друпала для данного модуля.
hook_update_N in developer/hooks/install.php
Производит обновление таблиц БД, необходимое для единичного обновления модуля.
menu_edit_menu_validate in modules/menu/menu.admin.inc
Validates the human and machine-readable names when adding or editing a menu.
menu_get_item in includes/menu.inc
Получает элемент роутера.
menu_link_children_relative_depth in includes/menu.inc
Находит глубину потомков пункта по отношению к глубине пункта.
menu_nodeapi in modules/menu/menu.module
Реализация hook_nodeapi().
node_feed in modules/node/node.module
A generic function for generating RSS feeds from a set of nodes.
node_update_index in modules/node/node.module
Реализация hook_update_index().
pager_query in includes/pager.inc
Выполняет «постраничный» запрос к базе данных.
profile_admin_settings_autocomplete in modules/profile/profile.admin.inc
Retrieve a pipe delimited string of autocomplete suggestions for profile categories
profile_autocomplete in modules/profile/profile.pages.inc
Callback to allow autocomplete of profile text fields.
statistics_title_list in modules/statistics/statistics.module
Returns all time or today top or last viewed node(s).
system_update_6021 in modules/system/system.install
Migrate the menu items from the old menu system to the new menu_links table.
taxonomy_autocomplete in modules/taxonomy/taxonomy.pages.inc
Вспомогательная функция для автозаполнения формы с терминами таксономии
taxonomy_select_nodes in modules/taxonomy/taxonomy.module
Находит все ноды, которые соответствуют выбранным условиям таксономии.
user_autocomplete in modules/user/user.pages.inc
Menu callback; Retrieve a JSON object containing autocomplete suggestions for existing users.
user_block in modules/user/user.module
Реализация hook_block().
_blog_post_exists in modules/blog/blog.module
Helper function to determine if a user has blog posts already.
_comment_update_node_statistics in modules/comment/comment.module
Updates the comment statistics for a given node. This should be called any time a comment is added, deleted, or updated.
_forum_new in modules/forum/forum.module
Находит первую непрочтённую ноду для заданного форума.
_menu_find_router_path in includes/menu.inc
Find the router path which will serve this path.
_menu_update_parental_status in includes/menu.inc
Проверяет и обновляет статус 'has_children' для родительской ссылки.
_node_access_rebuild_batch_operation in modules/node/node.module
Batch operation for node_access_rebuild_batch.

Код

<?php
function db_query_range($query) {
  $args = func_get_args();
  $count = array_pop($args);
  $from = array_pop($args);
  array_shift($args);

  $query = db_prefix_tables($query);
  if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one array' syntax
    $args = $args[0];
  }
  _db_query_callback($args, TRUE);
  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback', $query);
  $query .= ' LIMIT '. (int)$from .', '. (int)$count;
  return _db_query($query);
}
?>

Пользовательские комментарии

Функция позволяет передавать переменные через шаблоны подстановки. Например:
RETURN db_result(db_query_range("SELECT tid FROM {term_data} WHERE name = '%s'", $name, 0, 1));
Также можно передавать переменные в SQL-запрос одним ассоциативным массивом - это описано выше в статье.

PS.
В Drupal 7 сигнатура будет более расширеной:
db_query_range($query, $from, $count, array $args = array(), array $options = array())

Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Вход в систему