簡體   English   中英

如何在此代碼中使用LIKE運算符?

[英]How can i use LIKE operator in this code?

這是我的搜索引擎php代碼。 我在數據庫中有三個字段:標題,說明和網址。 但它只會顯示與標題匹配的搜索查詢。 如何創建與標題,描述和網址匹配的搜索查詢?

<?php

ini_set('display_errors',0); // turn off php notice  & errors


$button = $_GET ['submit'];
$search = $_GET ['search'];

if(strlen($search)<=1)
echo "Search term too short";
else{
echo "You searched for <b>$search</b> <hr size='1'></br>";
mysql_connect("localhost","woogle","woogle");
mysql_select_db("search");                  

$search_exploded = explode (" ", $search);

foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="title LIKE '%$search_each%'";
else
$construct .="AND title LIKE '%$search_each%'";
}


$constructs ="SELECT * FROM searchengine WHERE $construct";

$run = mysql_query($constructs);

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

嘗試這個:

foreach($search_exploded as $search_each)
{
    $x++;
    $search_each_e = mysql_real_escape_string($search_each);    // To help prevent SQL injection
    if($x==1)
        $construct .="(title LIKE '%$search_each_e%' OR description LIKE '%$search_each_e%' OR url LIKE '%$search_each_e%')";
    else
        $construct .="AND (title LIKE '%$search_each_e%' OR description LIKE '%$search_each_e%' OR url LIKE '%$search_each_e%')";
}

您可以轉義字符串以防止SQL注入 但是,我認為使用准備好的語句是一種更可靠的方法。

嘗試這個 :

 $construct = " 1 " 

 foreach($search_exploded as $search_each)
 {
   $construct .=" AND (title LIKE '%$search_each%' OR description LIKE '%$search_each%' OR url LIKE '%$search_each%')";
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM