Wordpress mysql_fetch_array()期望参数1是资源错误

时间:2017-02-21 17:43:28

标签: php mysql wordpress

使用mysql非常新,但是,我正在尝试修复wordpress插件中旧代码中的错误 - 这是原始代码:

        $sql = mysqli_query("SELECT count(`question_count`) as Qcount FROM `wp_posts` WHERE `question_count` = 1 and `question_date` = '".date("Y-m-d")."'") or die(mysql_error());  

        $no_of_questions = get_option( 'askme_setting_no_of_questions', 10 );
            if($row = mysql_fetch_array($sql)) {        
                $qry = $row['Qcount'];  
            }       
            if($qry >= $no_of_questions) {      
                $value = "The question limit for today has been reached";           
                $button = "disabled";   
            } else {        
                $value = "Add your question to the cart";           
                $button = " ";  
            }  

出现以下错误:

mysqli_query() expects at least 2 parameters, 1 given in

我已经改变了第一行,如下所示使用Wordpress函数:

$sql = $wpdb->get_results( "SELECT count(`question_count`) as Qcount FROM `wp_posts` WHERE `question_count` = 1 and `question_date` = '".date("Y-m-d")."'" ); 

现在出现以下错误:

mysql_fetch_array() expects parameter 1 to be resource, array given in ...
Undefined variable: qry in ...

有什么明显的事我在这里做错了吗?

3 个答案:

答案 0 :(得分:1)

你正在混淆。

mysql_mysqli_是PHP中两个完全不同的函数集。您无法使用mysqli_功能发送查询,并使用mysql_*操纵结果。

此外,mysql_函数在PHP5的更高版本中已弃用,并在PHP7中完全删除。

您最好的选择是遵循@ tadman的建议,并使用WP的API。

答案 1 :(得分:1)

您应首先进行mysqli连接,然后使用查询并进一步获取查询。您可以按照以下链接使用mysqli fetch查询。

https://www.w3schools.com/php/func_mysqli_fetch_array.asp

答案 2 :(得分:0)

您是否只更改了$sql =行?

来自wordpress codex:

global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );

应该按documentation返回一个数组或结果对象。 所以你的代码不需要做任何fetch_assoc相关的方法。 Wordpress正在处理实际的数据库连接和查询解析,只是将结果交给你。

可能的解决方案:

// formatting for readability.
$date = date("Y-m-d");
// Prepare query.
$sql = $wpdb->prepare(
  "SELECT count(`question_count`) as Qcount 
  FROM `wp_posts` 
  WHERE `question_count` = 1 
  AND `question_date` = %s",
  $date
);
// Execute query.
$results = $wpdb->get_results($sql);

// Get option for number of questions.
$no_of_questions = get_option( 'askme_setting_no_of_questions', 10); 

// Set base values to avoid usage of else condition.  
$value = "Add your question to the cart";
$button = " ";

// Check to ensure results returned.
if (!empty($results)) {
  // Evaluate result of query.
  if ($results[0]->Qcount >= $no_of_questions) {
    // Update values only if necessary.
    $value = "The question limit...";
    $button = "disabled";
  }
}