如何禁用%输出所有内容

时间:2015-04-25 16:27:21

标签: php html mysql search

嘿,我有一个搜索字段,我正在从我的数据库中搜索某些内容,现在我在测试后看到了问题,如果我放了"%"在搜索字段中,它将输出我准备搜索的所有内容。有没有办法禁用它?

<h3>Search Share Details</h3>
<p>You may search either by company name or issue date</p>

<form name = "search" method = "get">
<input type = "text" name = "share" size = "40" maxlength="50">
<input type = "submit" value = "Search">
</form>

获取内容连接到数据库,获取结果并打印

function get_contents() {

   if(isset($_GET['share']))
    {
        $conn = db_connect();
        $shares = get_shareSearch($conn);
        db_disconnect($conn);
        $contents = array('shares' => $shares);
        return $contents;
    }
    else
    {
        $conn = db_connect();
        $shares = get_share($conn);
        db_disconnect($conn);
        $contents = array('shares' => $shares);
        return $contents;
    }
}


function print_contents($contents) 
{

    if(count($contents['shares']) == 0)
    {
        echo "<script type = 'text/javascript'>alert('Sorry but share is not found! Q_Q');</script>";

    }
    else
    {
    ?>   
        <table>
            <tr>
                <th>Company Name</th>
                <th>Rate</th>
                <th>Issue Date</th>

            </tr>
    <?php
    foreach ($contents['shares'] as $share) 
    {
        print "<tr>";
        $identifier = urlencode($share['SHAREID']);
        print "<td><a href='share-details.php?id={$identifier}'>{$share['COMPANY']}</a></td>";
        print "<td>{$share['RATE']}</td>";

        $issue_date = $share['ISSUE_DATE'];
        $issue_date = $issue_date === NULL ? "&lt; not available &gt;" : $issue_date;
        print "<td>{$issue_date}</td>";
        print "</tr>";
    }
    ?>
        </table>
    <?php
    }
}
//require("shares.php");
require("search.php");
?>

自行查询

function get_shareSearch($conn) { 
$id = "";
if(isset($_GET['share'])){$id = $_GET['share'];}
$statement = db_create_statement($conn, "SELECT DISTINCT * FROM shares  WHERE(company LIKE '{$id}' OR issue_date LIKE '{$id}')");
$resultset = db_fetch_resultset($statement); 
return $resultset; 

}

2 个答案:

答案 0 :(得分:1)

逃避

这指的是在其前面加上一个字符来表示它的字面意思:

原始声明

SELECT * FROM ikeaTable WHERE chair LIKE '5% off';

转义版本

SELECT * FROM ikeaTable WHERE chair LIKE '5\% off' ESCAPE '\';

<强> YOURS

SELECT DISTINCT * FROM shares WHERE(company LIKE '\%{$id}' OR issue_date LIKE '\%{$id}') ESCAPE '\'

答案 1 :(得分:0)

我不知道您正在使用哪个数据库库,但您当然需要将您包含的参数转义到查询中。如果没有被转义,MySQL会将%理解为一个特殊字符,基本上意味着匹配任何东西&#39;。

我建议您阅读数据库库文档(或代码)以了解如何将查询参数包含到语句中或如何直接转义它们。