根据用户ID创建搜索按钮

时间:2014-08-27 17:04:27

标签: php mysql

我想进行搜索。当我在文本框中键入用户ID并按下提交按钮时,它会显示用户数据。怎么会这样呢?我知道这种编码有点不对劲。顺便说一句我管理员,想找到用户。

<?php
include 'config1.php';
$query = "SELECT * FROM login WHERE userid LIKE '%$searchTerm%'"
$result = mysql_query($query);
echo "<table height = '30%'border='1'>";

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    echo "<tr>";
    echo "<td width='5%'><b>USER ID:</b> {$row['userid']} </td>";
    echo "<td width='5%'><b>USER NAME :</b> {$row['username']} </td>";
    echo "<td width='5%'><b>USER EMAIL:</b> {$row['useremail']} </td>";
    echo "<td width='5%'><b>USER DIVISION:</b> {$row['userdiv']} </td>";
    echo "<td width='5%'><b>USER DEPARTMENT:</b> {$row['userdepartment']} </td>";
} 
echo"</table>";
?>

2 个答案:

答案 0 :(得分:1)

取自your comment

  

当我在网站上运行时,它说Parse错误:语法错误,意外&#39; $结果&#39;第41行的C:\ xampp \ htdocs \ viewAdmin.php中的(T_VARIABLE)

此行中有一个缺少的分号:

$query = "SELECT * FROM login WHERE userid LIKE '%$searchTerm%'"
                                                                ^

DO

$query = "SELECT * FROM login WHERE userid LIKE '%$searchTerm%'";

另外,要使用$searchTerm,您需要使用名为&#34; search&#34;例如。 <input type = "text" name = "search">然后执行:

$searchTerm = $_POST['search'];

使用POST表单方法。

<form method = "post" action = "your_SQL_file.php">

  Search: <input type = "text" name = "search">

 <input type = "submit" name = "submit" value = "Search">

</form>

<?php 
include 'config1.php';
$searchTerm = $_POST['search'];
$query = "SELECT * FROM login WHERE userid LIKE '%$searchTerm%'";

...

修改(全部在一个文件中)

<form method = "post" action = "">

  Search: <input type = "text" name = "search">

 <input type = "submit" name = "submit" value = "Search">

</form>


<?php
include 'config1.php';

if(isset($_POST['submit'])){

$searchTerm = mysql_real_escape_string($_POST['search']);

$query = "SELECT * FROM login WHERE userid LIKE '%$searchTerm%'";
$result = mysql_query($query);

    echo "<table height = '30%'border='1'>";

    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
        echo "<tr>";
        echo "<td width='5%'><b>USER ID:</b> {$row['userid']} </td>";
        echo "<td width='5%'><b>USER NAME :</b> {$row['username']} </td>";
        echo "<td width='5%'><b>USER EMAIL:</b> {$row['useremail']} </td>";
        echo "<td width='5%'><b>USER DIVISION:</b> {$row['userdiv']} </td>";
        echo "<td width='5%'><b>USER DEPARTMENT:</b> {$row['userdepartment']} </td>";
    }
    echo"</table>";

} // brace for submit isset
?>

答案 1 :(得分:0)

您(可能)在源代码中存在安全漏洞,使其容易受到SQL注入攻击。

$query = "SELECT * FROM login WHERE userid LIKE '%$searchTerm%'"

如果您没有过滤或清理$searchTerm,那么您需要打开一个洞来注入SQL。

我强烈建议您阅读PDO,特别是prepared statements"Are PDO prepared statements sufficient to prevent SQL injection?"