如果没有从数据库中找到记录则回显消息

时间:2012-12-06 16:23:20

标签: php

我创建了一个搜索框,它将从MySQL数据库中提取某些参数。如果没有参数出现,我需要将哪些代码嵌入到以下代码中,从而导致回显文本通知用户没有匹配的参数可能很好。

<?php
mysql_connect ("localhost", "root", "")  or die (mysql_error());
mysql_select_db ("store_location");

$term = $_POST['term'];

$sql = mysql_query("SELECT * FROM store_location where store_name like '%$term%' or     address like '%$term%' or city like '%$term%' or state like '%$term%' or zip like     '%$term%' or phone like '%$term%' or fax like '%$term%' or email like '%$term%' or url     like '%$term%' ");

echo '<h1>Search Results:</h1>';

while ($row = mysql_fetch_array($sql)){

echo 'Store Name: '.$row['store_name'];
echo '<br/> Address: '.$row['address'];
echo '<br/> City: '.$row['city'];
echo '<br/> State: '.$row['state'];
echo '<br/> Zip: '.$row['zip'];
echo '<br/> Phone: '.$row['phone'];
echo '<br/> Fax: '.$row['fax'];
echo '<br/> Email: <a href="mailto:'.$row['email'].'">'.$row['email'].'</a>';
echo '<br/> URL: <a href="'.$row['url'].'">'.$row['url'].'</a>';
echo '<br/><br/>';
}

?>

4 个答案:

答案 0 :(得分:1)

while...行之前添加此内容:

if( mysql_num_rows($sql) == 0) echo "<p>No matches</p>";

docs

答案 1 :(得分:1)

要获取表格中的记录数,您可以尝试以下代码:

<?php
$query = mysql_query("select count(*) as total from table_name");
$result = mysql_fetch_array($query);
echo $result['total'];
if( $result['total']==0)
{
echo "no records is found";
}else{
echo"numbers of records is=".$result['total'];
}

?>

答案 2 :(得分:0)

试试这个。 mysql_num_rows

if(mysql_num_rows($sql)){
    while ($row = mysql_fetch_array($sql)){
        echo 'Store Name: '.$row['store_name'];
        echo '<br/> Address: '.$row['address'];
        echo '<br/> City: '.$row['city'];
        echo '<br/> State: '.$row['state'];
        echo '<br/> Zip: '.$row['zip'];
        echo '<br/> Phone: '.$row['phone'];
        echo '<br/> Fax: '.$row['fax'];
        echo '<br/> Email: <a href="mailto:'.$row['email'].'">'.$row['email'].'</a>';
        echo '<br/> URL: <a href="'.$row['url'].'">'.$row['url'].'</a>';
        echo '<br/><br/>';
    }
}else{
    echo 'No results found';
}

答案 3 :(得分:0)

<?

$term = mysql_real_escape_string($_POST['term']); // sanitize input!
if ($sql = mysql_query('...')) { // mysql_* functions are deprecated, consider mysqli instead
    $count = mysql_num_rows($sql);
    echo "<h1>$count Result" . ($count == 1 ? '' : 's') . ' Found' . ($count ? ':' : '') . '</h1>';
    while ($row = mysql_fetch_array($sql)) {
        echo '...';
    }
}