在PHP中检查查询字符串值

时间:2009-11-16 22:53:56

标签: php mysql query-string

http://localhost/?area=characters&name=Michal+Stroganof



$result = mysql_query("SELECT * from players WHERE name = '$_GET[name]'");

while ($row = mysql_fetch_assoc($result)) {

    echo "Name: " .$row['name']. "<br>";
    echo "Level: " .$row['level']. "<br>";

}

这是我的characters.php的所有代码

如果URL中不包含get变量“name”,我想显示搜索表格播放器的搜索表单。我该怎么做?

3 个答案:

答案 0 :(得分:9)

你的意思是只改变你的SQL字符串吗?

$sql = 'SELECT * from players';
if (isset($_GET['name'])) {
    $safename = mysql_real_escape_string($_GET['name']);
    $sql .= " WHERE name='$safename'";
}
$result = mysql_query($sql);

务必清理SQL!

答案 1 :(得分:5)

使用isset()

if (isset($_GET['name'])) {
    // your above code
} else {
    // display form        
}

答案 2 :(得分:1)

又快又脏:

<?php
if (!isset($_GET['name']))
{
    echo  '<form action="'. $_SERVER['PHP_SELF'] .'" method="GET">'
         .'<input type="text" name="name" />'
         .'</form>';
}
else
{
    // your current code that queries your database here
}
?>