翻译:似曾相识 http://www.drupaluser.org
允许使用相同的代码原理在不同的服务器上应用.
Drupal为开发人员提供了一个数据库抽象层,轻松有效的支持多种数据库服务器。这一层的意图是可能多的维护SQL的语法和功能,但也允许开发人员以统一的方式影响复杂的功能。在适当的时候它还为建设动态查询提供了一个结构化接口,和实施安全检查和类似的好方法。
该系统是建立在PHP's PDO ( PHP的数据对象)的数据库API和继承其大部分的语法和语义。
例如,有人可能希望返回某一用户撰写的最近10个节点的名单。取代SQL查询的直接问题.
SELECT n.nid, n.title, n.created FROM node n WHERE n.uid = $uid LIMIT 0, 10;
?>
调用Drupal 函将替代这种方式:
$result = db_query_range('SELECT n.nid, n.title, n.created
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid), 0, 10);
foreach($result as $record) {
// Perform operations on $node->title, etc. here.
}
?>
大括号用来围绕“节点” ,以提供表前缀通过数据库连接: :表前缀( ) 。明确使用一个用户ID传递给db_query ( ) ,以便发觉并且制止用户输入SQL注入攻击。由于数据库服务器之间语法的限制,从而使抽象到db_query_range ( )参数。最后,请注意PHP的数据对象能够对foreach ( )的结果设定。
所有的数据库操作传递作为一份声明字符串。一份声明是一个“模板”的查询,忽略文字或变量值有利于占位符。这些值将成为这些占位符是通过单独的数据库驱动程序和处理插入值查询到在一个安全的方式。这意味着你永远不应该引用或字符串转义值插入查询。
有两种格式的占位符:命名和未命名。指定的占位符强烈倾向于在所有情况下,因为它们更灵活和自我记录。指定的占位符应当开始一个冒号“ : ”可后面跟着一个或多个字母,数字或下划线。
指定的占位符开始,冒号,后面再加一个独特的字符串。例如:
SELECT nid, title FROM {node} WHERE uid=:uid
?>
“ :uid”是一个占位符将被替换掉的文字值时,执行查询。特定的占位符标签不能重复在一个特定的查询,即使该值应该是相同的。当使用指定的占位符,数组的参数查询必须是一个关联数组在按键的占位符标签(如:uid)并且其值是相对应使用的值。该数组可以任意排序。
未命名的占位符只是一个问号。例如:
SELECT nid, title FROM {node} WHERE uid=?
?>
In this case, the array of arguments must be an indexed array of values to use in the exact same order as the placeholders in the query.
Note that placeholders should be a "complete" value. For example, when running a LIKE query the SQL wildcard character, %, should be part of the value, not the query itself. Thus, the following is incorrect:
SELECT nid, title FROM {node} WHERE title LIKE :title%
?>
It should instead read:
SELECT nid, title FROM {node} WHERE title LIKE :title
?>
and the value for :title should include a % as appropriate. Again, note the lack of quotation marks around :title. Because the value is not inserted into the query as one big string but as an explicitly separate value, the database server knows where the query ends and a value begins. That is considerably more secure against SQL injection than trying to remember which values need quotation marks and string escaping and which don't.
INSERT, UPDATE, and DELETE queries need special care in order to behave consistently across all different databases. Therefore, they use a special object-oriented API for defining a query structurally. For example, rather than
INSERT INTO node (nid, title, body) VALUES (1, 'my title', 'my body')
?>
one would instead write:
$fields = array('nid' => 1, 'title' => 'my title', 'body' => 'my body');
db_insert('my_table')->fields($fields)->execute();
?>
This method allows databases that need special data type handling to do so, while also allowing optimizations such as multi-insert queries. UPDATE and DELETE queries have a similar pattern.
Drupal also supports transactions, including a transparent fallback for databases that do not support transactions. To start a new transaction, simply call $txn =db_transaction(): in your own code. The transaction will remain open for as long as the variable $txn remains in scope. When $txn is destroyed, the transaction will be committed. If your transaction is nested inside of another then Drupal will track each transaction and only commit the outer-most transaction when the last transaction object goes out out of scope, that is, all relevant queries completed successfully.
Example:
function my_transaction_function() {
// The transaction opens here.
$txn = db_transaction();
$id = db_insert('example') ->fields(array( 'field1' => 'mystring', 'field2' => 5, )) ->execute();
my_other_function($id);
return $id; // $txn goes out of scope here, and the entire transaction commits. }
function my_other_function($id) { // The transaction is still open here. if ($id % 2 == 0) { db_update('example') ->condition('id', $id) ->fields(array('field2' => 10)) ->execute(); } }
?>
函数
名称 | 位置 | 描述 |
db_affected_rows | includes/database/database.inc | Determine the number of rows changed by the preceding query. |
db_and | includes/database/query.inc | Returns a new DatabaseCondition, set to "AND" all conditions together. |
db_condition | includes/database/query.inc | Returns a new DatabaseCondition, set to the specified conjunction. |
db_delete | includes/database/database.inc | Returns a new DeleteQuery object for the active database. |
db_distinct_field | includes/database/database.inc | Wraps the given table.field entry with a DISTINCT(). The wrapper is added to the SELECT list entry of the given query and the resulting query is returned. This function only applies the wrapper if a DISTINCT doesn't already exist in the query. |
db_driver | includes/database/database.inc | Retrieve the name of the currently active database driver, such as "mysql" or "pgsql". |
db_escape_table | includes/database/database.inc | Restrict a dynamic table, column or constraint name to safe characters. |
db_insert | includes/database/database.inc | Returns a new InsertQuery object for the active database. |
db_is_active | includes/database/database.inc | Determine if there is an active connection. |
db_last_insert_id | includes/database/database.inc | Returns the last insert id. |
db_merge | includes/database/database.inc | Returns a new MergeQuery object for the active database. |
db_or | includes/database/query.inc | Returns a new DatabaseCondition, set to "OR" all conditions together. |
db_placeholders | includes/database/database.inc | Generate placeholders for an array of query arguments of a single type. |
db_query | includes/database/database.inc | Execute an arbitrary query string against the active database. |
db_query_range | includes/database/database.inc | Execute an arbitrary query string against the active database, restricted to a specified range. See alsoDatabaseConnection::defaultOptions() |
db_query_temporary | includes/database/database.inc | Execute a query string against the active database and save the result set to a temp table. See alsoDatabaseConnection::defaultOptions() |
db_rewrite_sql | includes/database/database.inc | Rewrites node, taxonomy and comment queries. Use it for listing queries. Do not use FROM table1, table2 syntax, use JOIN instead. |
db_select | includes/database/database.inc | Returns a new SelectQuery object for the active database. |
db_set_active | includes/database/database.inc | Sets a new active database. |
db_transaction | includes/database/database.inc | Returns a new transaction object for the active database. |
db_update | includes/database/database.inc | Returns a new UpdateQuery object for the active database. |
db_xor | includes/database/query.inc | Returns a new DatabaseCondition, set to "XOR" all conditions together. |
pager_query | includes/pager.inc | Perform a paged database query. |
tablesort_sql | includes/tablesort.inc | Create an SQL sort clause. |
update_sql | includes/database/database.inc | Perform an SQL query and return success or failure. |
_db_check_install_needed | includes/database/database.inc | Redirect the user to the installation script if Drupal has not been installed yet (i.e., if no $databases array has been defined in the settings file) and we are not already there. Otherwise, do nothing. |
_db_query_process_args | includes/database/database.inc | Backward-compatibility utility. |
_db_rewrite_sql | includes/database/database.inc | Helper function for db_rewrite_sql. |