我正在尝试创建可以按标题和类别ID获取数据的查询。下面简单的查询在phpMyAdmin中为我工作。
`SELECT * FROM `ws_promotion` AS prm LEFT JOIN `ws_pro_cat` AS prmCat ON prm.`pm_id` = prmCat.`pm_id`
WHERE prmCat.`cat_id` = 3 AND prm.`pm_title` LIKE '%Essa%' `
我正在使用PDO,所以我必须根据PDO程序进行转换。我正在尝试下面两个查询,但这些都是返回错误。
$PromotionSts=$this->pdoConnection->prepare("SELECT * FROM `ws_promotion` AS prm LEFT JOIN `ws_pro_cat` AS prmCat ON prm.`pm_id` = prmCat.`pm_id`
WHERE prmCat.`cat_id` = :cat_id AND prm.`pm_title` LIKE ? ");
$PromotionSts->bindParam(':cat_id', $cat_id);
$PromotionSts->bindParam(':pm_title', '%$pm_title%');
$cat_id = $cat_id;
$pm_title = $pm_title;
$PromotionSts->execute();
$PromotionSts=$this->pdoConnection->prepare("SELECT * FROM `ws_promotion` AS prm LEFT JOIN `ws_pro_cat` AS prmCat ON prm.`pm_id` = prmCat.`pm_id`
WHERE prmCat.`cat_id` = :cat_id AND prm.`pm_title` LIKE ? ");
$PromotionSts->execute(array(3,'%Essa%'));
如果有人就此向我提出建议,我将不胜感激。谢谢
答案 0 :(得分:3)
如果您仔细阅读了prepare
manual ,您会注意到
SQL语句可以包含零个或多个命名(:name)或问号(?)参数标记,在执行语句时将替换实际值。您不能在同一SQL语句中同时使用命名和问号参数标记;选择一个或其他参数样式。
所以,正确的查询是:
$PromotionSts=$this->pdoConnection->prepare("SELECT * FROM `ws_promotion` AS prm LEFT JOIN `ws_pro_cat` AS prmCat ON prm.`pm_id` = prmCat.`pm_id`
WHERE prmCat.`cat_id` = :cat_id AND prm.`pm_title` LIKE :pm_title");
// Both query parameteres are named parameters
$PromotionSts->bindParam(':cat_id', $cat_id);
// variables in single quotes are NOT parsed
$PromotionSts->bindParam(':pm_title', '%' . $pm_title . '%');
// this lines are useless
//$cat_id = $cat_id;
//$pm_title = $pm_title;
$PromotionSts->execute();
或者:
$PromotionSts=$this->pdoConnection->prepare("SELECT * FROM `ws_promotion` AS prm LEFT JOIN `ws_pro_cat` AS prmCat ON prm.`pm_id` = prmCat.`pm_id`
WHERE prmCat.`cat_id` = ? AND prm.`pm_title` LIKE ? ");
// Both query parameteres are ? marks
$PromotionSts->execute(array(3,'%Essa%'));