动态构建PHP PDO MySQL查询

时间:2016-05-17 17:55:43

标签: php mysql pdo

我正在转换网站上的旧式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创建的变量是正确的,所以我确定这是因为我错过了对准备部分如何解释信息的理解,但我需要向正确的方向推进。

2 个答案:

答案 0 :(得分:5)

你有两个问题。首先,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,很难找到适合您使用的内容,但只需说明您添加到查询中的每个条件,就必须添加如果您计划继续创建动态查询,则另一个绑定参数。这样做的逻辑比我在这里演示的要复杂得多。

答案 1 :(得分:0)

像布兰查德先生所指出的那样,你似乎无意中在你的LIKE条款中增加了两个占位符而不是一个。它应该是:

            <?php
            // RIGHT AFTER THE LIKE YOU HAD 2 PLACE-HOLDERS: ? ? RATHER THAN JUST 1: ?
            if (xxxxx) {
                // YOU ARE CONCATENATING "AND" DIRECTLY TO THE $furthersort VARIABLE WITHOUT A SPACE: WRONG...
                // $furthersort = $furthersort."AND age_birth='yes' ";
                $furthersort    = $furthersort." AND age_birth='yes' ";
            }
        if (xxxxx) {
                // YOU ARE CONCATENATING "AND" DIRECTLY TO THE $furthersort VARIABLE AGAIN WITHOUT A SPACE: WRONG...
                // $furthersort = $furthersort."AND age_three='yes' ";
                $furthersort    = $furthersort." AND age_three='yes' ";
            }

        ...

        $prequery  = "SELECT id from products WHERE product_categories LIKE '%";
        $prequery .= $catid . "%' " . $furthersort. " ORDER BY product_name ASC "; // <== WHITE SPACE IS GRATIS IN MYSQL


        $sql        = "SELECT id from products WHERE product_categories LIKE :CAT_ID ORDER BY product_name ASC";
        $query      = $objDb->prepare($sql);
        // $params3 = array('%$catid%', $furthersort);      <==  VARIABLE INSIDE SINGLE QUOTES!!! YOU MAY USE DOUBLE QUOTES...
        $params3    = array("CAT_ID"=>"%" . $catid . "%" . $furthersort);
        $query->execute($params3); 
        while ($row = $query->fetch(PDO::FETCH_ASSOC));