2012-09-09 81 views
0

我正在尝试使用下面的if/else语句来构建查询,但我在第一步中对NULL求值时出现问题。无效的MySQL资源

经过一些在线搜索后,我似乎无法追查我做错了什么......应该使用空引号代替:""
虽然这也给了我一个错误。

所以我不知道问题是在第一个块还是第二个,即while循环。

有什么建议吗?

$name = $_POST['Your_name']; 

if ($location != "All" && $name == NULL) $query="SELECT * FROM talent WHERE duty_station='$location')"; 
else if($location == "All" && $name != "All") $query="SELECT * FROM talent WHERE Your_name IN ('$name')"; 
else if($dutyReq != "All" && $name == "All") $query="SELECT * FROM talent WHERE duty_station='$location'"; 
else if($location == "All" || $name == "All") $query="SELECT * FROM talent"; 

然后我的循环,打印出的数据给了我这个错误:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /var/www/html/talent/searchresults.php on line 64

这是错误来自代码:

$result=mysql_query($query); 
    mysql_query($result); 

    echo "<table border='1'> 
    <tr> 
    <th>Your name</th> 
    <th>duty station</th> 
    <th>first proficiency</th> 
    </tr>"; 
    while($row = mysql_fetch_array($result)){ 
     echo "<tr>"; 
     echo "<td>" . $row['Your_name'] . "</td>"; 
     echo "<td>" . $row['duty_station'] . "</td>"; 
     echo "<td>" . $row['prof_order_processing'] . "</td>"; 
     echo "</tr>"; 
     } 
echo "</table>"; 
+1

看起来你在这里的SQL语句有错误“SELECT * FROM talent WHERE duty_station ='$ location'----->)” –

+3

**你的代码容易受到SQL注入的攻击**你真的*应该使用[准备语句](http://stackoverflow.com/a/60496/623041),将变量作为参数传递到其中,而这些参数不针对SQL进行评估。如果你不知道我在说什么,或者如何解决它,请阅读[Bobby Tables]的故事(http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain) 。 – eggyal

+0

在PHP中,'null'是小写字母。 –

回答

1

您的第一个SQL查询错误(一个额外的右括号):

$query="SELECT * FROM talent WHERE duty_station='$location')"; 

它应该是:

$query="SELECT * FROM talent WHERE duty_station='$location'"; 

随着这些代码行:

$result=mysql_query($query); 
mysql_query($result); 

你想达到什么目的?您正试图使用​​MySQL资源作为查询字符串。
删除第二行。


如果没有设置$_POST['name'],你会看到

Notice: Undefined index: name in <filename> on line X

为了解决这个问题,使用此代码:

$name = empty($_POST['name']) ? null : $_POST['name']; 

要记住,对SQL注入安全代码。

mysql_*功能不鼓励使用,您应该使用PDO来代替。
您可以使用PDO::prepare使您的代码更安全。

+0

它看起来像这两个仍然存在:mysql_query($ result); $ result = mysql_query($ query); – richfranzen

+0

@ user1658726你不需要'mysql_query($ result);',它会抛出一个错误。删除该行。 –

0

在PHP中,你应该写的东西像这样

$name = $_POST['Your_name']; 
if(isset($name) && !empty($name)) 
{ 
    //some code 
} 

Als啊,你可以添加更多的检查,像is_array(如果你希望普通字符串),等..

+3

为什么你将isset()与empty()结合使用?你只能使用empty(),因为如果变量没有设置,它不会产生警告...... –

+0

@glavić:真的吗?很高兴知道。我从来没有用过它,因为我认为它会...... thx。 – Kuro

+2

我会对$ _POST ['Your_name']'进行检查。另外,严格地说,你应该使用'=== null'或'is_null()'作为'0 == null',''''' –

1

我认为这个问题是这一行:

mysql_query($result); 

它不应该存在。你不能调用mysql_query函数,并给它一个不是sql脚本的变量。 删除这一行。

+0

我试过评论这一点,但同样的错误依然存在。 – richfranzen