dopgv00024 2016-05-17 17:55
浏览 50
已采纳

动态构建PHP PDO MySQL查询

I am converting old-style MySQL/PHP queries on a site. I have a page that has a series of checkboxes. This is submitted, and a query is built based on what checkboxes are checked (there are at least 6 like the following):

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";

I'm trying to move the second part this over to PHP like this:

$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));

But it's not working. The variables created by the if's are correct, so I'm sure it's because I am missing an understanding of how the prepare portion interprets the information, but I need a push in the right direction.

  • 写回答

2条回答 默认 最新

  • duangan7834 2016-05-17 18:14
    关注

    You have two problems. First you can only have one bound argument for the LIKE condition, so you have to state that and the subsequent conditions:

    $query = $objDb->prepare("SELECT id from products WHERE product_categories LIKE ?  AND age_three = ? ORDER BY product_name ASC");
    

    Now you can send two values in the array

    $furthersort = 'yes';
    $params3 = array("%$catid%", $furthersort);
    

    Now, given that we do not know how you set $furthersort it is hard to come up with something exact for you to use but suffice it to say for each condition you add to the query, you have to add another bound parameter if you plan to continue along the lines of creating dynamic queries. the logic for doing that is much more complex than I have demonstrated here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值