douzhu6149 2015-11-22 21:44
浏览 107
已采纳

PHP MySQL通过html <input>搜索并显示行

I have an HTML form like:

<form  action = "get-row.php"  method = "post" >                  
<input type = "text"  name = "mess_username" />
<input type = "submit" name = "submit" />
</form>

And my "get-row.php" is like :

$button = $_POST ['submit'];
$search = $_POST ['mess_username'];

if (!$button) {
    echo "you didn't submit a keyword";
}
else {
    if (strlen($search) <= 1) {
        echo "Search term too short";
    }
    else {
        echo "You searched for <b> $search </b> <hr size='1' >";
    }
}

I am now successfully getting the value I have searched for. My next approach is to search the $search from my Database. I am trying like:

mysql_connect("server", "user", "pass");
mysql_select_db("my_db");

My Final "ok" Code after currection :

$sql = " SELECT * FROM messbd WHERE mess_username= '$search' ";
$run = mysql_query($sql);

$foundnum = mysql_num_rows($run);

if ($foundnum == 0) {
    echo "Sorry, there are no matching result for <b> $search </b>";
}
else {
    echo "$foundnum results found !<p>";

    while ($runrows = mysql_fetch_assoc($run)) {
        $mess_username = $runrows ['mess_username'];
        $mess_email = $runrows ['mess_email'];
        $android_app = $runrows ['android_app'];

        echo " $mess_username  <br> $mess_email <br> $android_app ";
    }
}

The problem is, I am getting the message that, "There are no matching results!" So what will be the correction there?

The problem is solved now & The code is updated above. Thanks.

  • 写回答

3条回答 默认 最新

  • duanshan1977 2015-11-22 21:58
    关注

    Since your $search results will be a string, then you need to quote that variable in your query. I'm pretty sure that you're looking for a string in your database, seeing echo "you didn't submit a keyword"; and mess_username being a user's "name".

    WHERE mess_username='$search' ";
    

    assuming an exact match. If you're looking for something that resembles your search, say you're looking for "foot" and want to find "football", then use LIKE.

    Also add or die(mysql_error()) to mysql_query() just in case there may be errors, and it seems that there would be, when not quoting a string in a query's variable.

    Footnotes:

    Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.


    Plus, it's best to use a conditional empty() against your input.

    I.e.:

    if(!empty($_POST[ 'mess_username' ])){
    ...
    }
    

    should someone just click without entering anything, which could throw you an error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 matlab求解平差
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法