dqu92800 2011-11-30 21:59
浏览 125
已采纳

匹配PHP中的关键字

i have a search function on my website where users can search for products. it works perfectly fine except for the fact that when a user searches for 'ipod' it comes up with no result as the name of the product is 'apple ipod'. how do i code it so that when part of the name of the product is searched, the correct product comes up?

my code is as follows:

    <div id="search" align="right">
<form action="" method="get">
  <span id="sprytextfield1">
  <input name="search" id="search2" type="text" width="250px"/>
  <span class="textfieldRequiredMsg"></span></span>
  <input name="" type="submit" value="Search"/>
</form></div>
<br /><br />
<h2>Your Search Results For "<?php echo $_GET['search'] ?>":</h2><hr />

    <table border="0" cellpadding="2px" width="600px">
        <?
        $search = $_GET['search'];

            $result=mysql_query("select * from products WHERE name = '$search'")
            or die(mysql_error());
if (mysql_num_rows($result) == 0) {
       echo '&nbsp;'.'Could Not Be Found';
    }   
    else {

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

        ?>
        <tr>
            <td><?php echo'<img src="getImage.php?id=' . $row['serial'] .'"/>'
?>            </td>
            <td>    <b><a href="pdaproduct.php?product_id=<?=$row['serial']?>"><?=$row['name']?></a></b><br />
                    Price:<big style="color:green">
                        £<?=$row['price']?></big><br /><br />
                    <input type="button" value="Add to Cart" onclick="addtocart(<?=$row['serial']?>)" />
            </td>
        </tr>
        <tr><td colspan="2"><hr size="1" /></td>

        <? 
            }
    }?>
    </table>

thanks for any advice given! :)

  • 写回答

3条回答 默认 最新

  • duanjitong7226 2011-11-30 22:01
    关注

    Ignoring the fact that your code should never be used for production (it's unsafe), you should use a LIKE in your query.

    mysql_query("select * from products WHERE name LIKE '%$search%'")
    

    Now, optimized against SQL injections and other things you don't want, this would become:

    mysql_query("select * from products WHERE name LIKE '%".mysql_real_escape_string($search)."%'")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效