我正在转换网站上的旧式MySQL/PHP查询。我有一个页面有一系列的复选框。这将被提交,并根据选中的复选框生成查询(至少有6个复选框如下所示):
if (xxxxx) {
$furthersort=$furthersort."AND age_birth='yes' ";
}
if (xxxxx) {
$furthersort=$furthersort."AND age_three='yes' ";
}
...
$prequery = "SELECT id from products WHERE product_categories LIKE '%$catid%' ".$furthersort."ORDER BY product_name ASC";
我试图将第二部分移到PHP中,如下所示:
$query = $objDb->prepare("SELECT id from products WHERE product_categories LIKE ? ? ORDER BY product_name ASC");
$params3 = array('%$catid%',$furthersort);
$query->execute($params3);
while ($row = $query->fetch(PDO::FETCH_ASSOC));
但没用。if创建的变量是正确的,所以我确信这是因为我缺少对prepare部分如何解释信息的理解,但是我需要朝正确的方向推进。
最佳答案
你有两个问题。首先,对于LIKE
条件,只能有一个绑定参数,因此必须声明该参数以及随后的条件:
$query = $objDb->prepare("SELECT id from products WHERE product_categories LIKE ? AND age_three = ? ORDER BY product_name ASC");
现在可以在数组中发送两个值
$furthersort = 'yes';
$params3 = array("%$catid%", $furthersort);
现在,考虑到我们不知道如何设置
$furthersort
很难找到精确的数据供您使用,但足以说明您添加到查询中的每个条件,如果您计划继续沿着创建动态查询的路线进行,则必须添加另一个绑定参数。这样做的逻辑比我在这里演示的要复杂得多。关于php - 动态构建PHP PDO MySQL查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37283214/