2013-01-02 46 views
-2

數據庫連接是正確的,但我得到一個錯誤說我的MySQL數據庫搜索代碼有什麼問題?

Warning: 
mysql_fetch_array(): supplied argument is not a valid MySQL result on line 31 

<?php 
    $hostname = "localhost"; 
    $username = "user"; 
    $password = "pass"; 
    $usertable = "products"; 
    $dbName = "test_prods"; 


$s = $_GET["s"]; 
$name = $row["product_name"]; 

    MYSQL_CONNECT($hostname, $username, $password) OR DIE("Unable to connect to database"); 
    @mysql_select_db("$dbName") or die("Unable to select database"); 

//error message (not found message) 
    $XX = "No Products Found"; 


$query = mysql_query("SELECT * FROM $usertable WHERE $s LIKE '$name'"); 
    while ($row = mysql_fetch_array($query)) 
    { 
     $variable1=$row["row_name1"]; 
     $variable2=$row["row_name2"]; 
     $variable3=$row["row_name3"]; 
print ("this is for $variable1, and this print the $variable2 end so on..."); 
} 

//below this is the function for no record!! 
if (!$variable1) 
    { 
     print ("$XX"); 
    } 
//end 
?> 
+2

你可以在調用'mysql_query'後查看'mysql_error'來查看是否有任何問題運行你的查詢。 –

+1

'$ name = $ row [「product_name」];'---請解釋這一行 – zerkms

+1

請注意,舊的mysql_%函數將被停用。這意味着您的代碼在PHP升級時可能會停止工作。對於新項目,您應該按照[PHP文檔中推薦的](http://www.php.net/manual/en/mysqlinfo.api.choosing.php)切換到mysqli擴展。 –

回答

0

你似乎可以用一個未定義的變量:

$name = $row["product_name"]; 

我猜你正在嘗試從另一個查詢中獲取名稱,然後使用它來獲取匹配(如果有的話)。

在致電mysql_query之前設置名稱很可能會爲您完成這項工作。

另外,從它的外觀你剛剛開始與MySQL,所以讓我建議你放棄學習使用mysql_函數,並開始學習如何使用PDO運行您的查詢。

我發現this tutorial相當有幫助。

1

在你的sql語法中可能有一個錯誤。

在這條線在這裏

$name = $row["product_name"]; 

不$行[ 「PRODUCT_NAME」]評價什麼嗎?

從你發佈的內容看,它沒有,但也許有一個值在其他地方加載。

如果它不計算任何東西,那麼sql語句將在語法中出現錯誤,並且$ query不能成爲mysql資源。

2

變化:

$s = $_GET["s"]; 
$name = $row["product_name"]; 

要:

$s = mysql_real_escape_string($_GET["s"]); 
$name = mysql_real_escape_string($row["product_name"]); 

被警告注意這個警告: *此擴展不贊成PHP 5.5.0的,並會在將來被移除。相反,應使用的MySQLi或PDO_MYSQL擴展名爲*

信息:http://php.net/manual/en/function.mysql-real-escape-string.php


和您的查詢更改爲:

$query = mysql_query("SELECT * FROM $usertable WHERE $s LIKE '$name'") 
     or die(mysql_error()); 

會告訴你是否有在你的SQL中的錯誤這將縮小問題的範圍!如果你能告訴我你得到了什麼結果,我可以更新更適合問題的答案。