我有以下代码 -
<?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%但未打印任何结果。
答案 0 :(得分:1)
您必须在查询中连接您要搜索的变量
$sql= "SELECT * FROM products WHERE product_name ='".$terms."'";
或
$sql= "SELECT * FROM products WHERE product_name LIKE '%".$terms."%'";
答案 1 :(得分:1)
使用此:
$sql = "SELECT * FROM products WHERE product_name ='$terms'";
无需连接。
答案 2 :(得分:0)
如果您在mysql 5.5或更低版本上使用innodb引擎,则必须像这样使用“LIKE”:
$sql= "SELECT * FROM products WHERE product_name like '%".$terms."%'";
如果你使用的是mysql 5.6,或者你正在使用myisam表,那么如果你在搜索的列上有全文索引,则可以使用MATCH AGAINST。
$sql= "SELECT match(product_name) against('".$terms."') as relevance
FROM products
WHERE relevance>0
ORDER BY relevance desc";
请查看参数化查询,或者至少使用mysql_real_escape_string来清理变量。
答案 3 :(得分:0)
我为mysql创建了一个函数,用于解析百分比排序的字符串。如果你愿意,你可以使用它。
它几乎可以找到您搜索的所有组合。
首先你需要在mysql中创建一个函数。这是代码。 我在phpmyadmin
中做到了DELIMITER //
CREATE FUNCTION search ( search VARCHAR(255), string VARCHAR(255) )
RETURNS FLOAT
BEGIN
DECLARE searchlength INT;
DECLARE charcount INT DEFAULT 1;
DECLARE ch VARCHAR(10);
DECLARE a INT DEFAULT 0;
DECLARE b INT DEFAULT 1;
DECLARE c INT DEFAULT 0;
SET searchlength = LENGTH(search);
WHILE charcount <= searchlength DO
SET ch = SUBSTRING(search,charcount,1);
IF LOCATE(ch,string) > 0 THEN
IF LOCATE(ch, string) - 1 = b THEN
SET c = c + 1;
END IF;
SET b = LOCATE(ch, string, b);
SET a = a + 1;
END IF;
SET charcount = charcount + 1;
END WHILE;
IF searchlength = a THEN
RETURN (c/30)*100;
END IF;
RETURN -1;
END; //
DELIMITER ;
现在,当您从php进行mysql调用时,可以使用此函数。
$searchneedle = "Some string you like to search for"
SELECT name,username
FROM users
WHERE search(LOWER('$searchneedle'),CONCAT(LOWER(test_cullum))) > -1
ORDER BY search(LOWER('$searchneedle'),CONCAT(LOWER(test_cullum))) DESC