Drupal如何SQL查询传递参数?

Drupal使用称之为“placeholder”的方式处理SQL查询参数:

<?php
// WRONG:
$result = db_query("SELECT nid, title FROM {node} WHERE type = ':type'", array(
  ':type' => 'page',
));

// CORRECT:
$result = db_query("SELECT nid, title FROM {node} WHERE type = :type", array(
  ':type' => 'page',
));
?>

 

数组参数主要是应用于IN查询的环境:

<?php
// If the placeholder value to insert is an array, assume that we need
// to expand it out into a comma-delimited set of placeholders.

// This code:
db_query("SELECT * FROM {node} WHERE nid IN (:nids)", array(':nids' => array(13, 42, 144));

// Will get turned into this prepared statement equivalent automatically:
db_query("SELECT * FROM {node} WHERE nid IN (:nids_1, :nids_2, :nids_3)", array(
  ':nids_1' => 13, 
  ':nids_2' => 42, 
  ':nids_3' => 144,
));

// Which is equivalent to the following literal query:
db_query("SELECT * FROM {node} WHERE nid IN (13, 42, 144)");
?>

 

参考:Drupal Static queries

你可能感兴趣的:(drupal)