[英]PHP MYSQL Using IN() with CASE and Like in PDO
I've been trying to implement an IN statment in my PDO sql. 我一直在尝试在我的PDO sql中实现IN语句。 I've succesfully implemented a simple using the solution found in Using PDO with IN
我已经成功使用在IN中使用PDO的解决方案实现了一个简单的方法
My code is as follows: 我的代码如下:
$in_array = array("INTERNAL SITE","SUPPLIER");
$in = str_repeat('?,', count($in_array) - 1) . '?';
$dbname = $_SESSION['dbname'];
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $db->id, $db->pass);
//connect to db
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//error modes
$sql = "SELECT cs_id, name, alias, fk_cs_type as type, is_active as active
FROM companysite WHERE ( fk_cs_type IN ($in))";
$stmt = $conn->prepare($sql);
$stmt->execute($in_array);
However my end goal is to also implement CASE and Like clause referencing an additional 2 variables ($srchBy and $srchField). 但是,我的最终目标是也实现引用另外2个变量($ srchBy和$ srchField)的CASE和Like子句。 When I try to do this I get a HY093 error.
当我尝试执行此操作时,出现HY093错误。 What am I doing wrong in this code?
我在这段代码中做错了什么?
$in_array = array("INTERNAL SITE","SUPPLIER");
$in = str_repeat('?,', count($in_array) - 1) . '?';
$srchBy = "ALIAS";
$dbname = $_SESSION['dbname'];
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $db->id, $db->pass);
//connect to db
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//error modes
$sql ="SELECT cs_id, name, alias, fk_cs_type as type,
is_active as active FROM companysite
WHERE ( fk_cs_type IN ($in)) AND
((CASE WHEN $srchBy = 'ALIAS' THEN alias ELSE name END)
LIKE $srchField)";
$stmt = $conn->prepare($sql);
$stmt->execute($in_array);
Currently, your final SQL will look something like this: 当前,您的最终SQL将如下所示:
SELECT
cs_id,
name,
alias,
fk_cs_type as type,
is_active as active
FROM
companysite
WHERE
( fk_cs_type IN ('INTERNAL SITE','SUPPLIER')) AND
((CASE WHEN 'ALIAS' = 'ALIAS' THEN alias ELSE name END) LIKE 'value_of_$srchField_variable')
Unless you plan turning the statement into a MySQL View, why not consider using php conditionals to build a cleaner, less complex SQL statement. 除非计划将语句转换为MySQL视图,否则为什么不考虑使用php条件语句构建更简洁,更简单的SQL语句。
$sql = "SELECT cs_id, name, alias, fk_cs_type as type, is_active as active
FROM companysite
WHERE ( fk_cs_type IN ($in) )";
if($srchBy == 'ALIAS')
{
$sql.= " AND alias LIKE $srcField";
}
else
{
$sql.= " AND name LIKE $srcField";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.