我正在学习php,我试图做一个“搜索引擎”真的很简单但它现在有效,我遇到的问题是,如果我从这行代码中删除%
符号,
$query_params = array(':search' => mysql_real_escape_string("%".$search."%"));
并在搜索框中输入%sam%
,代码将这些符号作为查询的一部分读取而不是常规字符,我试图修复但我不知道如何:/
这里是完整的PHP代码
<?php
require("../login/connect.php");
$search = $_GET['query'];
$query = "SELECT * FROM mobiles WHERE (`name` LIKE :search) or (`type` LIKE :search)";
$query_params = array(':search' => mysql_real_escape_string("%".$search."%"));
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
$count = $stmt->rowCount();
$min_length = 3;
if(strlen($query) >= $min_length)
{
echo "<table border='0' width='600' align='center' cellpadding='1'>";
echo "<tr align='center' bgcolor='#03acfa' >
<td height='35px' width='200px'><b>Mobile Name</b></td>
<td><b>Mobile Type</b></td>
</tr>";
if ($count > 0)
{
foreach($rows as $row):
{
echo "<tr align='center' bgcolor='#93dafb'>
<td height='25px'>". $row['name'] ."</td> <td>".$row['type']."</td>
</tr>" ;
}
endforeach;
}
else
{
echo "<tr align='center' bgcolor='#fdee03'><td colspan='2' height='25px'>Sorry..No results for $search</td><tr>";
echo "</table>";
}
}
HTML
<form action="search.php" method="get" >
<input type="text" name="query" id="text" />
<input type="submit" name="submit" id="search" value="Search" />
</form>