Drupal 7中的数据库查询

时间:2012-06-13 03:01:08

标签: mysql drupal drupal-7

我正在尝试在drupal中运行db查询,其中内容类型有一个节点关联字段,我正在尝试获取该类型的所有注释,其中当前节点的NID与指定的任何节点匹配说明关联领域。

一个直观的例子

Nodetype1   - 节点关联字段

NodeType2

我想得到节点关联字段与当前加载的Nodetype2的NID匹配的所有Nodetype1。

我当前的数据库查询是这样的:

db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid);

并且没有返回任何内容,当我知道这样的节点存在的事实时,我也尝试删除WHERE语句并返回如下数组:

DatabaseStatementBase Object ( [dbh] => DatabaseConnection_mysql Object ( [shutdownRegistered:protected] => [target:protected] => default [key:protected] => default [logger:protected] => [transactionLayers:protected] => Array ( ) [driverClasses:protected] => Array ( [SelectQuery] => SelectQuery [DatabaseSchema] => DatabaseSchema_mysql [MergeQuery] => MergeQuery [DatabaseTransaction] => DatabaseTransaction [UpdateQuery] => UpdateQuery [InsertQuery] => InsertQuery_mysql ) [statementClass:protected] => DatabaseStatementBase [transactionSupport:protected] => 1 [transactionalDDLSupport:protected] => [temporaryNameIndex:protected] => 0 [connectionOptions:protected] => Array ( [database] => cityhound_dev [username] => blahblah [password] => blahblah [host] => localhost [port] => [driver] => mysql [prefix] => Array ( [default] => ) ) [schema:protected] => DatabaseSchema_mysql Object ( [connection:protected] => DatabaseConnection_mysql Object *RECURSION* [placeholder:protected] => 0 [defaultSchema:protected] => public [uniqueIdentifier:protected] => 4fd7fba9e563e2.50177866 ) [prefixes:protected] => Array ( [default] => ) [prefixSearch:protected] => Array ( [0] => { [1] => } ) [prefixReplace:protected] => Array ( [0] => [1] => ) ) [queryString] => SELECT * FROM field_data_field_promo_profile )

任何人都有一些想法吗?

2 个答案:

答案 0 :(得分:0)

db_query()返回一个可迭代对象,所以你只需要迭代它:

$result = db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid);

foreach ($result as $row) {
  $entity_id = $row->entity_id;
  // etc...
}

答案 1 :(得分:0)

您应该在查询中使用参数来阻止SQL注入。

例如,上面的查询应如下所示:


$result = db_query("SELECT * FROM {field_data_field_promo_profile} p
   WHERE p.field_promo_profile_nid = :nid ", array(':nid' => $N->nid);

foreach ( $result as $row ) {
  $entity_id = $row->entity_id;
  // etc...
}