2011-04-01 49 views
2

嗨我收到錯誤「Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/**/**/locate.php on line 16」。警告:mysql_num_rows():提供的參數不是有效的MySQL結果資源

我已經雙重檢查了一切,谷歌搜索/ Stackoverflow搜索,並找不出爲什麼它這樣做。希望有任何想法!

getdate.php

function getDeals($the_type) { 
$result = mysql_query(" 
    SELECT * 
    FROM deals 
    WHERE deal_type = '" . $the_type . "' 
     "); 
} 

locate.php?類型=樂趣

$type = $_GET['type']; 
include("getdata.php"); 

getDeals($type); 
if (mysql_num_rows($result)) { 
    echo '<ul>'; 
    while($row = mysql_fetch_array($result)) 
     { 
     echo '<a href="deal.php?i=' . $row["i"] . '">'; 
     echo '<li class="deal ' . $row["deal_type"] . 'deal">'; 
     echo '<h3>' . $row["deal_title"] . '</h3>'; 
     echo '</li>'; 
     echo '</a>'; 
     } 
    echo '</ul>'; 
} 
else { 
    echo '<div class="nodeals">None</div>'; 
} 
+1

可能重複[mysql_fetch_assoc():提供的參數不是在PHP中一個有效的MySQL結果資源(http://stackoverflow.com/questions/1858304/mysql-fetch-assoc-supplied-argument-is-not-a-valid-mysql-result-resource-in-ph) – 2011-09-16 17:50:05

+0

[Warning:mysql_fetch_array():提供的參數不是有效的MySQL的結果](http://stackoverflow.com/questions/795746/warning-mysql-fetch-array-supplied-argument-is-not-a-valid-mysql-result) – 2012-08-09 20:21:22

回答

7

你不能從你的getDeals函數返回的結果,所以它是沒有定義在腳本的主體中。

function getDeals($the_type) { 
    $result = mysql_query("SELECT * 
          FROM deals 
          WHERE deal_type = '" . $the_type . "'"); 
    return $result; 
} 

$result = getDeals($type); 

,並確保您的$ the_type值驗證和轉義(或更好,但使用PDO),以防止SQL注入

+0

謝謝@ mark-baker - 將驗證/轉義只涉及更改$ type = $ _GET ['type'];到$ type = mysql_real_escape_string($ _ GET ['type']); ? – Jamie 2011-04-01 22:24:44

+0

這將確保包含引號字符的字符串值不會破壞SQL查詢...但您應始終驗證從用戶輸入傳遞的值(例如$ _GET和$ _POST變量)以及......如果該值應該是一個整數數字,請確保它確實是一個整數數字。 – 2011-04-01 22:27:43

0

您需要導入$結果到函數作爲一個全球性的:

function getDeals($the_type) { 
    global $result; 
    $result = mysql_query(" 
     SELECT * 
     FROM deals 
     WHERE deal_type = '" . $the_type . "' 
    "); 
} 

然而,這是不設置這種類型的事情了一個好辦法。你應該改用PDO之類的東西,或者返回一個合適的資源標識符。

0

有很多方法可以解決這個問題,但最好的方法是返回mysql資源,然後將該資源分配給$result變量。

function getDeals($the_type) { 
    return mysql_query(" 
     SELECT * 
     FROM deals 
     WHERE deal_type = '" . $the_type . "' 
    "); 
} 

$result = getDeals($type); 
0

作爲一個經驗法則,99%的錯誤是由於給定的或緊接在前面的行或語句。在你的情況下,其他人首先注意到,getDeals($type)不返回結果。

你也應該調用mysql_query()更改爲類似:

function getDeals($the_type) { 
    $query = " 
     SELECT * 
     FROM deals 
     WHERE deal_type = '" . $the_type . "' 
      "; 

    $result = mysql_query($query) or trigger_error(mysql_error().$query); 

    return $result; 
} 
相關問題