我的MySQL数据库搜索代码有什么问题?

时间:2013-01-02 00:31:01

标签: mysql database search

数据库连接完全正确,但我收到错误

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  
?>

3 个答案:

答案 0 :(得分: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中是否存在错误以解决问题!如果你能告诉我你得到了什么结果我可以更新更适合这个问题的答案。

答案 1 :(得分:1)

你的sql语法可能有错误。

在这一行

$name = $row["product_name"];  

$ row [“product_name”]评估为什么?

从您发布的内容来看,它没有,但也许在其他地方加载了一个值。

如果它没有评估任何东西那么sql语句将在语法中出错并且$ query不能成为mysql资源。

答案 2 :(得分:0)

您似乎使用了未定义的变量:

$name = $row["product_name"];

我猜你试图从另一个查询中获取该名称,然后使用它来获取你的匹配项。

在致电mysql_query之前设置名称很可能会为您完成工作。

另外,从它的外观来看,你刚开始使用mysql,所以让我建议你放弃学习使用mysql_函数,并开始学习如何使用PDO运行你的查询。

我发现this tutorial非常有帮助。