db_result D6查询转换为db_select D7

时间:2015-06-02 22:02:26

标签: php drupal drupal-7

我正在尝试将此D6代码与查询转换为Drupal 7

   foreach ($order->products as $product) {
      if (db_result(db_query("SELECT nid FROM {the_table} WHERE fid = 'string' AND nid = %d", $product->nid))) {
       $nid[] = $product->nid;
       }
     }

我将其更改为查询:

    if (db_result(db_query('SELECT nid FROM {the_table} WHERE fid = 'string' AND nid = :nid', array(':nid' => $product->nid)))) {

然后以动态查询形式出现,我想是

   foreach ($order->products as $product) {
     $query = db_select('{the_table}', '');
     $query->fields('nid', array(''));
     $query->condition('fid', 'string');
     $query->condition('nid', ':nid');
     $query->execute();             
     $result = $query->fetchAssoc();
      foreach ($result as $record) {
      $product->nid;
      $nid [] = $product->nid;
        }
     }

我还尝试过" - > fetchfield();"在那里的陈述 - 相同的错误 我也试过:字符串而不是'字符串'

它会抛出此错误

PDOException:SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;查看与您的MySQL服务器版本相对应的手册,以获得正确的语法,以便使用附近的&AS;来自the_table the_table WHERE(fid =' string')AND'在第1行:SELECT nid。 AS FROM {the_table} the_table WHERE(fid =:db_condition_placeholder_0)AND(nid =:db_condition_placeholder_1);进程()中的数组([:db_condition_placeholder_0] =>字符串[:db_condition_placeholder_1] =>:nid)(/。...模块的第450行)。

另外我不知道为什么错误会显示两个" the_table" - 一个接一个 - 所以有可能otrignal D6查询不好吗?

有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:0)

我没有足够的注意,在新的查询格式中括号不是正确的语法。它有效 - 我在https://www.drupal.org/dynamic-queries

再次阅读动态查询页面后看到其他地方出错了
 <?php
  $query = db_select('the_table', 'the_table');
  $query->fields('the_table', array('nid'));
  $query->condition('the_table.fid', 'string');
  $query->condition('the_table.nid', $product->nid);
  $query->execute();
  ?>

答案 1 :(得分:0)

您应该修正以下错误:

// error
$query = db_select('{the_table}', '');
// fixed
$query = db_select('TABLE_NAME', 'TABLE_ALIAS'); // remove the curly braces. The second argument is for you to choose an alias for your table.

// error
$query->fields('nid', array(''));
// fixed
$query->fields('nid', array('id', 'name')); // Choose the fields you want to return from the query.

// error
$query->condition('nid', ':nid');
// fixed
$query->condition('nid', $someVariable, '='); // no need to use ':nid'