douju1365 2016-12-19 02:11
浏览 13
已采纳

PHP用户搜索

I am creating a search bar on my website so users can search for other users and it works but if I enter one username , all of the usernames show up. How can I only show the user I am looking for and if the user isn't registered give an else statement ?

search.php :

<?php
include("connect.php");

GLOBAL $usernam;

$output = '';

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

if (empty($_POST["searchbar"])) {
echo"You didn't enter anything . ";
} else {

$searchq = $_POST['Search'];
$searchq = preg_replace("#[^0-9a-z]#i", "",$searchq);

$query = mysqli_query($conn ,"SELECT * FROM users WHERE usernam LIKE '%$searchq%'") or die("Could not search");
$count = mysqli_num_rows($query);

 if($count == 0){

   echo "There was no search results . ";

 } else {

    while($row = mysqli_fetch_array($query)) {
        $usernam = $row['usernam'];
        $id = $row['id'];
        $output .= '<div>' .$usernam. '</div>';
    }

   }    
}
}
?>
<html>
<head>
<title>Interpage</title>
</head>
<body>

<?php print("$output");  ?>
</body>
</html>
  • 写回答

1条回答 默认 最新

  • dongyi5425 2016-12-19 02:34
    关注

    Your issue is that you are currently searching the value of your button, not your search bar -

    $searchq = $_POST['Search'];
    

    You want

    $searchq = $_POST['searchbar'];
    

    In regards to your question - is it secure ??. No, it is not. This is the perfect time to read up on How can I prevent SQL injection in PHP?

    At the bare minimum, you could use mysqli_real_escape_string()

    $searchq = mysqli_real_escape_string($conn, $_POST['searchbar']);
    

    but I would recommend to go a step further and learn how to use prepared statements/placeholders, ie.

    $stmt = $conn->prepare("SELECT * FROM users WHERE usernam LIKE ?");
    $stmt->bind_param('s', "%".$_POST['searchbar']."%");
    $stmt->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法