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条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度