php - PDO 数组到字符串的转换 - 参数

标签 php mysql arrays pdo parameters

很确定有一个简单的解决方法,但是当涉及到 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/

相关文章:

javascript - 如何使用 AJAX/PHP 编辑 mySQL 表中的一行?

PHP/SQL 使用一个 SELECT 语句从多个其他 lat/lng 位置获取所有 lat/lng 位置

mysql - 使用 LEFT JOIN 在查询中请求随机行

C++ `std::sort` 在不复制的情况下指向二维数据的指针

php - 带有 jQ​​uery 的 Ajax 请求不起作用

PHP shell_exec : how to copy a directory from one user to another (VPS on CentOs5)

php - 为什么 PHP 更喜欢 __call() 而不是 __callStatic()?

mysql - 如何从两个不同的表计算用户排名

java - 如何将字符串转换为二维整数数组?

arrays - SUM(IF) 有时只能查找数组中的第一个值