2017-02-21 42 views
0

很新的使用MySQL,但是,我試圖修復一塊舊的代碼中的bug的WordPress插件 - 這裏是原代碼:WordPress的mysql_fetch_array()預計參數1是資源錯誤

 $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 ... 

有什麼明顯的,我做錯了什麼?

+0

不要使用'mysqli'。獨家使用[WordPress數據庫層WPDB](https://codex.wordpress.org/Class_Reference/wpdb),不要混用。這裏真正的問題是你試圖使用'mysqli',而不是無意中使用糟糕的舊'mysql_query'界面。 – tadman

+0

@tadman完全同意你的觀點 - 我的目標是用$ wpdb替換對mysqli和mysql_query接口的引用(正如你從第一次更改中看到的那樣) - 但是,我不知道如何改變我的第二部分代碼適合第一個 - 如果這是有道理的 –

+0

你不能使用'mysql_fetch_array'或類似的東西。忘記這些功能,它們不相關,不兼容。 *獨佔*到WPDB功能。在文檔中,他們引用'get_row'來表示結果,等等。使用這些。 – tadman

回答

1

你在混合物。

mysql_mysqli_是PHP中兩組完全不同的函數。您不能使用mysqli_函數發送查詢,並使用mysql_*操縱結果。

另外,mysql_函數在PHP5的更高版本中已被棄用,並在PHP7中完全刪除。

最好的辦法是遵循@ tadman的建議,並使用WP的API來做到這一點。

+0

我打算寫一個答案,但這基本上是我要說的。我唯一要補充的是,它看起來像OP做了一個半心半意的嘗試,將'mysql'轉換爲'mysqli'。指出'mysql_query'和'mysqli_query'的方法簽名是不同的(因此解釋錯誤信息)也是有幫助的。 – HPierce

0

是您更改$sql =行的唯一行嗎?

從WordPress抄本:

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"; 
    } 
} 
相關問題