PDO通过引用传递参数

时间:2014-08-07 19:13:13

标签: php mysql pdo parameters

我正在尝试在PHP中创建一个函数,它将简化使用PDO访问我的数据库的过程。我有以下函数代码:

/**
* This function accepts a variable as well as a SQL query and evaluates that SQL query against the variable utilizing the PDO class.
* There is no return because the variables are modified by reference location, thus allowing you to continue to use them.
*
* @param $container The variable that will act as a container to hold the result of the SQL query.
* @param $fetch The variable that will store an array of the query's resulting data.
* @param $fetchStatus A boolean value that will determine how data is fetched. A 0 with result in a fetch and 1 will result in a fetchAll.
* @param $SQL The SQL query you wish to execute against the database as a string.
*/
function dbQuery(&$container, &$fetch, $fetchStatus, $SQL) {
    global $dbMain;

    $container = $dbMain->prepare($SQL);
    $container->execute();

    if($fetchStatus == 0) {
        $fetch = $container->fetch(PDO::FETCH_ASSOC); 
    }
    else {
        $fetch = $container->fetchAll(PDO::FETCH_ASSOC); 
    }

    return $container;
}

当我使用& $容器以及$ SQL参数时,该函数完全正常。但如果我这样做,我必须手动获取数据。我通过引用传递$ fetch变量,因为我认为函数会获取数据并只是改变那个内存位置?我对它如何运作的理解可能不正确。

我的问题是此功能不适用于以下代码:

$test = dbQuery($test, "Select name FROM events WHERE eventID=5083250", $testFetch, 0); echo $testFetch['name']; 

我将其添加到我的代码实际上导致我的页面的其余部分从那里开始并向前停止渲染,而是显示为空白。对于此特定代码行,我还在错误日志中获得了“无法通过引用传递参数2”。

另外,我想补充一点,我知道有几个帖子具有相同的错误代码,但它们似乎正在使用BindParam和BindValue。我不确定那些确实做了什么,但它们似乎与我的问题无关。

有谁知道如何通过引用正确传递两个参数并修改它们的值?

提前致谢!

1 个答案:

答案 0 :(得分:0)

看起来你已经以错误的顺序通过你的参数。

你的方法sig是:

function dbQuery(&$container, &$fetch, $fetchStatus, $SQL);

但是您尝试将参数2(SQL字符串)传递到&$fetch

尝试:

$test = dbQuery(
  $test,
  $testFetch,
  0,
  "Select name FROM events WHERE eventID=5083250"
)
相关问题