我正在编写一个脚本来循环用户点击的复选框,具体取决于单击哪些复选框将导致“动态”查询。我正在尝试使用数组构建一个where语句,以便在pdo中执行。
我遇到的问题是在foreach循环中我试图使用
=
连接字符串以构建我的查询。但是,当用户点击同一组复选框时,如
'why_and'
只会创建一个$ where,所以当我用var_dump打印出我的查询时,我得到了这个:
SELECT student.anum,
student.first,
student.last,
student.email,
session.aidyear,
reasons.reason,
COUNT(session.anum) as Total,
MIN(DATE_FORMAT(session.signintime, '%b %d, %Y - %l:%i %p')) as 'First',
MAX(DATE_FORMAT(session.signintime, '%b %d, %Y - %l:%i %p')) as 'Last'
FROM
student INNER JOIN session
ON session.anum = student.anum
INNER JOIN session_status
ON session_status.status = session.status
INNER JOIN reasons
ON reason_id = session.why
WHERE 1 AND why = :reason
GROUP BY session.anum
然后我var_dump占位符数组并得到它:
[ “:原因”] => string(9)“4,5,6”}
注意我在:reason数组中有三个值,在查询中只有1:reason。有什么我想念的吗?
这是我的思考过程的一个例子(请看一下评论):
$placeholder = array();
$where = "";
if($and !== "") // This is the "super array" if you will
{
if(array_key_exists('why_and', $and)) // Now I check for each specific thing a user can search for in the array / database
{
foreach($and as $key => $value) // Take the $value of the array index why_and
{
$where .= " AND why = :reason "; // Create a where variable with a named placer holder for each value that exists in the array
$placeholder[':reason'] .= rtrim($value, ' ,'); // Then add to the $placeholder array so I can I add it to the PDO execute as an array
}
}
if(array_key_exists('status_and', $and))
{
foreach($and as $key => $value)
{
$where .= " AND status = :status ";
$placeholder[':status'] .= rtrim($value, ' ,');
}
}
}
$finSQL = $sql . ' WHERE 1 ' . $where; // COncate the final results
$dynamic = $this-> db-> conn_id-> prepare($finSQL); // prepare
$dynamic-> execute($placeholder); // Use the placeholder array and pass that to the execute as a [key => value pair as shown in the manual example number 2][1]
编辑1 @Your Common Sense
只是为了清理这个工作,但只针对每个复选框类别中的一个值,why_and,status_and但是如果我尝试从同一类别中执行更多一个值,那么它就不起作用。