PHP MySQL搜索&amp;通过html <input />显示行

时间:2015-11-22 21:44:19

标签: php mysql

我有一个HTML表单,如:

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

我的&#34; get-row.php&#34;就像:

$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' >";
    }
}

我现在成功获得了我搜索过的值。我的下一个方法是从我的数据库中搜索$ search。我想尝试:

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

我的决赛&#34;确定&#34;当前的代码:

$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 ";
    }
}

问题是,我收到的消息是,&#34;没有匹配的结果!&#34;那么那里的修正是什么?

现在问题解决了代码在上面更新。感谢。

3 个答案:

答案 0 :(得分:3)

您错过引用搜索字词

$sql = 'SELECT * FROM messbd WHERE mess_username="' . mysql_real_escape_string($search) . '"';

但是mysql扩展名已弃用,应该由PDO或mysqli替换。以下是PDO和准备语句的示例:

$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dbh = new PDO('mysql:host=server;dbname=my_db', 'user', 'pass', $options);

$sql = 'SELECT * FROM messbd WHERE mess_username=?';
$sth = $pdo->prepare($sql);
$sth->execute(array($search));
// there is no sure working rowCount, so fetch all and count
$rows = $sth->fetchAll(PDO::FETCH_ASSOC)
if (!$rows) {
    echo "Sorry, there are no matching result for <b> $search </b>";
} else {
    echo count($rows) . " results found !<p>";
    foreach ($rows as $row) {
        $mess_username = $row['mess_username'];
        $mess_email    = $row['mess_email'];
        $android_app   = $row['android_app'];
        echo "$mess_username<br>$mess_email<br>$android_app";
    }
}

答案 1 :(得分:2)

由于您的$search结果将是一个字符串,因此您需要在查询中引用该变量。我非常确定您在数据库中查找字符串,看到echo "you didn't submit a keyword";mess_username是用户&#34;名称&#34;。

WHERE mess_username='$search' ";

假设完全匹配。如果您正在寻找类似于您的搜索的内容,请说您正在寻找&#34; foot&#34;并希望找到&#34; football&#34;,然后使用LIKE。

同时将or die(mysql_error())添加到mysql_query()以防万一可能存在错误,并且在查询的变量中没有引用字符串时似乎会有。{/ p>

脚注:

您目前的代码向SQL injection开放。使用mysqli_* with prepared statementsPDOprepared statements

另外,最好对您的输入使用条件empty()

即:

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

如果有人只是点击而没有输入任何东西,这可能会给你一个错误。

答案 2 :(得分:0)

使用此查询,mysql将搜索为搜索的relarive值而设置的$ search输入。尝试使用单引号。