很确定有一个简单的解决方法,但是当涉及到 PDO 语句时,我在数组处理方面缺乏经验
目的:从数据库中检索一组id,然后使用这些id进行比较和检索
$SAList = getSecurityActionsForQuestion("$QID");
$con = database::getInstance()->getConnection();
$ParentList = $con->prepare('SELECT SQ.SurveyQuestionID, SQ.SurveyQuestionDesc
FROM SurveyQuestion SQ
JOIN SurveyQuestionLookup SQLP ON SQLP.SurveyQuestionID = SQ.SurveyQuestionID
WHERE SQLP.SecurityActionID IN (:SAList)
AND SQLP.SurveyQuestionID != :QID');
$ParentList->bindValue(':QID',$QID, PDO::PARAM_STR);
$ParentList->bindValue(':SAList',$SAList, PDO::PARAM_STR);
$ParentList->execute();
$Results = $ParentList->fetchAll();
现在,'getSecurityActionForQuestion' 函数和插入的选择语句分别起作用并检索我想要的内容。问题是我无法将数组发送到 PDO::PARAM_STR,而且我还没有找到解决此问题的方法。
我看到了一些用于内爆和准备字符串的选项,但我不完全确定如何将其合并到我当前的设计中。
有可能使用 foreach 循环来创建一个新数组,保存一个计数变量,然后在 SQL 语句中,我可以插入一堆命名参数,然后使用另一个 for 循环将每个参数绑定(bind)到它们各自的地方,但我敢肯定有人的流程比那个 hackjob 优雅得多。
编辑:
为了清楚起见,添加了 getSecurityActionsForQuestion(ID) 函数
function getSecurityActionsForQuestion($QID)
{
$con = database::getInstance()->getConnection();
$SAList = $con->prepare("SELECT DISTINCT SecurityActionID FROM SurveyQuestionLookup
WHERE SurveyQuestionID = :QID");
$SAList->bindValue(':QID',$QID,PDO::PARAM_INT);
$SAList->execute();
$Results = $SAList->fetchAll();
$SAList=null;
$con=null;
return $Results;
}
最佳答案
您可以使用 ?
占位符代替命名占位符,并使用值数组执行查询,而不是单独绑定(bind)每个值。 (参见 the PDOStatement::execute manual 中的示例 #5。)
$SAList = getSecurityActionsForQuestion("$QID");
$con = database::getInstance()->getConnection();
// create placeholders for each item in your array
$placeholders = rtrim(str_repeat('?,', count($SAList)),',');
$ParentList = $con->prepare("SELECT SQ.SurveyQuestionID, SQ.SurveyQuestionDesc
FROM SurveyQuestion SQ
JOIN SurveyQuestionLookup SQLP ON SQLP.SurveyQuestionID = SQ.SurveyQuestionID
WHERE SQLP.SecurityActionID IN ($placeholders)
AND SQLP.SurveyQuestionID != ?");
// add the $QID into the array
$SAList[] = $QID;
// execute the query with the array of values
$ParentList->execute($SAList);
$Results = $ParentList->fetchAll();
PDO::PARAM_STR
是默认绑定(bind)类型,因此无需指定即可用于此目的。
关于php - PDO 数组到字符串的转换 - 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41618932/