大家好,我正在编写一个简单的脚本,根据用户输入从整个数据库中搜索。 这是我的代码:
<?php
$search=isset($_POST['search']);
$submit=isset($_POST['submit']);
if($submit){
$connect=new mysqli("localhost","root","");
mysqli_select_db($connect,'go-web');
$query=mysqli_query($connect,"SELECT * FROM `go-web`.`product` WHERE (CONVERT(`name` USING utf8) LIKE '%$search%' OR CONVERT(`category` USING utf8) LIKE '%$search%' OR CONVERT(`brand` USING utf8) LIKE '%$search%' OR CONVERT(`keyword` USING utf8) LIKE '%$search%')");
while($row=mysqli_fetch_array($query))
{
echo '<tr><td style="height=100px"><center><a href=""><img src="'.$row['image'].'" width="150px" height="150px" /></a><center><figcaption>Price:'.$row['price'].'</figcaption></center><br> <center><figcaption>Stock:'.$row['stock'].'</figcaption></center></center></td></tr>';
}
}
?>
这里的问题是每当我给出输入时我会一次又一次得到相同的结果。 有帮助吗? 谢谢你。
答案 0 :(得分:2)
问题是您正在设置$search = isset($_POST['search'])
,这将产生一个布尔值,然后继续在您的查询中使用它:name LIKE '%$search%'
<?php
$search = $_POST['search'];
$submit = isset($_POST['submit']);
if(isset($search)) {
$connect = new mysqli("localhost","root","","go-web");
$search = mysqli_real_escape_string($connect, $search);
$sql = "SELECT * FROM `go-web`.`product` WHERE (CONVERT(`name` USING utf8) LIKE '%$search%' OR CONVERT(`category` USING utf8) LIKE '%$search%' OR CONVERT(`brand` USING utf8) LIKE '%$search%' OR CONVERT(`keyword` USING utf8) LIKE '%$search%')";
$query = mysqli_query($connect,$sql);
while($row = mysqli_fetch_array($query))
{
echo '<tr><td style="height=100px"><center><a href=""><img src="'.$row['image'].'" width="150px" height="150px" /></a><center><figcaption>Price:'.$row['price'].'</figcaption></center><br> <center><figcaption>Stock:'.$row['stock'].'</figcaption></center></center></td></tr>';
}
}
?>