PDO语句中是否可以有WHEN语句或IF语句?我已经尝试了以下方法,但是没有用

$stmt = $conn->prepare('SELECT company_id, name, alias, fk_company_type as type, is_active as active FROM company WHERE (CASE WHEN :srchBy = "alias" THEN alias ELSE name END)  LIKE :srchField');

$stmt->bindParam(':srchBy', $srchBy, PDO::PARAM_INT); //bind :srchField to $srchField in sql statement
$stmt->bindParam(':srchField', $srchField, PDO::PARAM_INT); //bind :srchField to $srchField in sql statement


表结构

company_id      |23980471998218241  | 23980471998218242       |
fk_company_type |HQ                 |SITE                     |
name            |JOHN PLUMBING HQ   |JOHN PLUMBING - BRIDGE ST|
alias           |CITY RD HQ         |BRIDGE ST SERVICE        |
is_active       |1                  |1                        |
created_date    |2015-04-18 19:35:32|2015-04-18 19:34:46      |

最佳答案

不幸的是,您不能按列名绑定参数。但是你可以做其他事情

$stmt = $conn->prepare('SELECT company_id, name, alias, fk_company_type as type, is_active as active FROM company WHERE (CASE WHEN "'.$srchBy.'" = "alias" THEN alias ELSE name END)  LIKE ?');
$stmt->bindValue(1, "%$srchField%", PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
print_r($result);


每个运算符/标识符必须经过硬编码,但是如果不是这种情况,则需要验证标识符

09-17 20:44