PHP 与 MySQL 的搜索功能

标签 php mysql search

我有以下代码 -

<?php # search.inc
error_reporting(E_ALL); // 
ini_set('display_errors', '1');
include "connect_to_mysql.php";
?>
<?php # search.inc.php

//header file:
include_once ('./includes/header.inc');
?>
<?php

$terms= $_GET['terms'];
echo "You've searched for: " . $terms;

$sql= "SELECT * FROM products WHERE product_name ='Big Tree'"; 
//-run  the query against the mysql query function 
$result=mysql_query($sql);

while ($row = mysql_fetch_array($result)) { // While there are products that match the search criteria, assign their data to a variable and echo their details on a webpage


             $id = $row["id"];
             $product_name = $row["product_name"];
             $price = $row["price"];
             $details = $row["details"];
             $category = $row["category"];
                echo '<br/> <img name="image" src="inventory_images/' . $row['id'] . '.jpg" width="100" height="150"/>';
                echo '<br/>';
                echo '<br/> Product Name: '.$row['product_name'];
                echo '<br/>';
                echo '<br/> <a href="modules/productsdetails.inc.php?id=' . $id . '">Click Here To View Product Page</a>';
                echo '<br/>';
                echo '<br/>';

        }
mysql_close(); //closes the MySQL connection.
?>
<?php
// Include footer file 
include_once ('./includes/footer.inc');
?>

如您所见 - 我已对其进行硬编码以搜索“Big Tree”。我的问题是 - 如何编码来搜索用户输入。

我已尝试%$terms%,但没有打印结果。

最佳答案

您必须在查询中连接要搜索的变量

$sql= "SELECT * FROM products WHERE product_name ='".$terms."'"; 

$sql= "SELECT * FROM products WHERE product_name LIKE '%".$terms."%'"; 

关于PHP 与 MySQL 的搜索功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15400184/

相关文章:

php-MySQL 到 JSON 数据冗余

php - 我可以在开关盒中使用 strpos 吗?

mysql - 是否规范化数据库?只读 MyISAM 表,性能是主要优先级(MySQL)

elasticsearch - 在Elasticsearch中查找与整个查询匹配的文档

php - Laravel 在 api 中间件上启用 csrf 保护

PHP/MySQL 点赞按钮

php - 如何使用数据库和 PHP 在 googlemap 上创建标记

php - 用php删除mysql表中的行

java - 在 Android 中的 List<String> 中快速搜索的方法

java - Jackrabbit 中 HTML 文档内的文本搜索