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 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题