[英]mysql select query 1 of the multiple values in selected field
我有另一个表单来上传1个产品的详细信息,这个产品有多个值(10),但我们说我们选择New Arrival,Black,White并上传到数据库。 所以现在我的数据库将字段名称设为'category',其值为New Arrival,Black,White。
现在我想做一个搜索功能,但每当我尝试运行它时,它就不会显示结果。 所以我做了2条记录,其中:
第1记录,字段类别和值'新到货'第2记录,字段类别和值'新到货,黑色,白色'
当我再次尝试运行我的代码时,它确实返回了第一条记录的结果,我尝试将相同的记录复制几行,结果证明它只能返回类别字段只有1个值的结果。
以下是我的代码的一小部分内容:
我对类别字段的添加记录表单输入是:
add_new.html
<select name="category[]" size="10" multiple="multiple">
<options>New Arrival</options>
<options>Black</options>
<options>White</options>
</select>
add_process.php
$category = implode(", ", $_POST['category']);
$strSQL = "INSERT INTO products_list (category) VALUES ('$category')";
search_form.html
<input type="text" name="search_text" />
<input type="submit" name="submit" />
search_process.php
$category = mysql_real_escape_string($_POST['product_category']);
$select = mysql_query("select image1, image2, image3, image4 from products_list WHERE category IN ('new arrival') ORDER BY id ASC");
while($row=mysql_fetch_array($select)) {
echo $row['image1'];
echo $row['image2'];
echo $row['image3'];
echo $row['image4'];
}
要重复我的问题,如何在该类别字段中获取包含(所需值)的行的结果?
接下来的问题是,类别值仅作为“新到货”存储在数据库中,如果我只键入“到达”而不是全名,如何获得返回结果? 目前,如果我只输入'到达',它也不会返回任何结果。
希望你们明白我想说的话。 先谢谢你们。
塞尔说:
$select = mysql_query("select image1, image2, image3, image4 from products_list WHERE category like '%new arrival%' ORDER BY id ASC");
为了便于参考,我在这里解释。
$catsearch = $_POST["category"];
$keywords = explode(' ', $catsearch); //if keywords entered is "white black new", will convert to array of "white","black","new". The delimiter here is the space.
$keywordsBits = array();
foreach ($keywords as $keyword) {
$keyword = trim($keyword);
if (!empty($keyword)) {
$keywordsBits[] = "category LIKE '%$keyword%'";
}
}
$result = mysql_query("SELECT * FROM products_list WHERE ".implode(' OR ', $keywordBits));
这将导致类似的查询
SELECT * FROM products_list WHERE category LIKE '%white%' OR category LIKE '%black%' OR category LIKE '%new%'
如果你想用“,”分隔关键字,你可以使用
$keywords = explode(',', $catsearch); //if keywords entered is "white,black,new arrival", will convert to array of "white","black","new arrival". The delimiter here is the comma.
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.