php pdo属性数组

问题描述 投票:0回答:1
---property---
id | ozellik
1  | "random"
2  | "fast"
3  | "red"
-----------

----property_cafe--------
id | cafe_id | property_id
1  | 1       |  1   
2  | 1       |  2
3  | 1       |  3
-----------------------

---cafe---
id | name
1  | lorem
-----------------

property.id = property_cafe.property_id
cafe.id = property_cafe.cafe_id 

复选框选择1,2,3。我希望看到具有1,2,3 id特征的咖啡馆的功能。

我可以创建一个单独的查询,但我有无限的功能表接近100,我找不到解决方案。

php sql arrays pdo
1个回答
0
投票

使用WHERE property.id IN (?, ?, ?, ...)创建查询,您可以根据复选框值数组的大小动态构建问号列表。

$where_count = count($_POST['property']);
$questions = '?' . str_repeat(', ?', $where_count-1);
$sql = "SELECT c.name, GROUP_CONCAT(p.ozellik) AS ozellik
        FROM cafe AS c
        JOIN property_cafe AS pc ON pc.cafe_id = c.id
        JOIN property AS p ON pc.property_id = p.id
        WHERE p.id IN ($questions)
        GROUP BY c.id
        HAVING COUNT(*) = ?";
$stmt = $pdo->prepare($sql);
$params = $_POST['property']; 
$params[] = $where_count;
$stmt->execute($params);

将数组传递给$stmt->execute()使用元素填充SQL中的?占位符。

有关编写查询以查找具有所有属性的所有咖啡馆的各种方法,请参阅How to return rows that have the same column values in MySql。这是制作此动态SQL的最简单方法。

假设您的复选框写成:

<input type="checkbox" name="property[]" value="1"> Random
<input type="checkbox" name="property[]" value="2"> Fast
<input type="checkbox" name="property[]" value="3"> Red

DEMO

© www.soinside.com 2019 - 2024. All rights reserved.