我真的很熟悉mysql,不能很好地理解什麼是解決我的問題的正確方法,所以如果有人有線索或解決方案,這是非常值得歡迎的,在這裏我們走。列出所選類別和價格範圍內的產品
我在DB兩個表:
產品:
- id_product
- name_product
- 等...
機生產線ct_category:
- id_product
- CATEGORY_NAME
當我保存一個產品和一個以上的類別,它看起來像這樣在我的數據庫:
id_product category_name
1 kids
1 men
在我HTML,我有這樣的一個表格:
<div class="checkbox">
<label><input type="checkbox" class="getcats" value="Women">Women</label>
</div>
<div class="checkbox">
<label><input type="checkbox" class="getcats" value="Men">Men</label>
</div>
<div class="checkbox">
<label><input type="checkbox" class="getcats" value="Kids">Kids</label>
</div>
<div class="form-group" id="range">
€ <input type="number" min="0" id="min" name="min" class="form-control" placeholder="0">
€ <input type="number" min="0" id="max" name="max" class="form-control" placeholder="100">
</div>
<button class="boton" id="request" onclick="request()">Request</button>
然後在我的JS文件,我讓Ajax調用:
function request(){
//get the values from price range
var min = jQuery("#min").val();
var max = jQuery("#max").val();
//create array to save the selected categories
var categories = [];
//save all the selected categories into the array
jQuery('.getcats').each(function(){
if(jQuery(this).is(":checked")){
categories.push(jQuery(this).val());
}
});
jQuery.ajax({
url: 'request.php',
method: 'POST',
data:{
categories:categories,
min:min,
max:max
},
success: function(data){
//on success, display data requested
},
dataType: 'json'
}); // End of ajax call
}
最後在我的PHP文件:
<?php
header("Content-type: text/javascript");
require_once($_SERVER['DOCUMENT_ROOT'].'/../../config.php');
$conn = mysqli_connect($servername, $username, $password, $db);
//here should be some code to validate price range (min and max)
//after validation assign to variables
$min = $_POST["min"];
$max = $_POST["max"];
//here some code to validate selected categories (checkboxes)
//after validation assign to variable
$categories = $_POST["categories"];
$categoriesList = implode("','",$Intersectedresult); //$intersectedresult comes from array_intersect($categorias,$checkCategorias)
$resultList = "'".$categoriasList."'";
//Before I had this query working well but only when a product had 1 category, but now each product can have more than 1 category so I don't know how to make that query
$randomProducts = $conn->query("SELECT * FROM products WHERE category_name IN ($resultList) && product_price BETWEEN $min AND $max ORDER BY rand() LIMIT 3")
?>
我研究了一點,發現一些術語,如INNER JOIN,但無法理解如何實現它能夠做到這樣的事情:
$randomProducts = $conn->query("SELECT products.product_name, products.product_image, products.product_desc, products.product_url, products.product_price FROM products INNER JOIN product_category ON product_category.category_name=women, kids or men");
希望有人能給我一個推動,非常感謝。
嗨阿爾貝託,感謝您的幫助。我正在嘗試你的代碼,並且出現這個錯誤:致命錯誤:在進行查詢之後,在這一行調用一個成員函數fetch_assoc()在布爾中''while($ row = $ randomProducts-> fetch_assoc() ){'任何線索? –