如何将MySQL_FETCH_ARRAY迁移到$wbpdb?

时间:2015-05-16 作者:mzurhorst

我正在将一个具有直接MySQL访问权限的脚本迁移到$wpdb类,但它失败了。下面是相邻的原始代码和新代码。怎么了?

<!-- 
##############################################################################

     PART 1:   OLD MYSQL FUNCTIONS 
--> 

<?php

function get_tag_data2() { 

  $result = mysql_query("SELECT * FROM ( SELECT lastname, count( lastname ) AS mycount FROM `tng_people` GROUP BY lastname ORDER BY count( lastname ) DESC LIMIT 0 , 35) AS presort order by rand()"); 
  while($row = mysql_fetch_array($result)) { 
    $arr[$row[\'lastname\']] = $row[\'mycount\'];
  }   
  return $arr;  
} 
?>


<!-- 
   ##############################################################################

     PART 2:   NEW WPDB FUNCTIONS 
--> 


<?php 
    global $wpdb;

function get_tag_data2() { 

  $tngnameresults = $wpdb->get_results("SELECT * FROM ( SELECT lastname, count( lastname ) AS mycount FROM `tng_people` GROUP BY lastname ORDER BY count( lastname ) DESC LIMIT 0 , 10) AS presort order by rand()"); 

  $arr = array();
  foreach ($tngnameresults as $result) {
        $arr[$result->lastname] = $result->mycount; 
   }
  return $arr;  
}
?>

1 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成

你不需要发布所有的代码就可以通过!问题在于:

<?php 
    global $wpdb;


function get_tag_data2() {
你需要global 内部功能-这就是the point of global:

<?php

function get_tag_data2() {
    global $wpdb;

    // Original function code
}

结束

相关推荐

$wpdb->替换/替换或更新主键

我编写代码将数据保存到数据库表中。如果表中存在行,我想替换该行;如果该行不存在,我想在表中插入新行。http://codex.wordpress.org/Class_Reference/wpdb我使用$wpdb->replace 函数,然后添加$wpdb->insert_id到代码末尾。对于更新所有字段,我使用主键替换“id”。我将id字段添加到数组中 $wpdb->replace( $wpdb->prefix . \'fafa\', array(