Skip to content
Advertisement

PDO : using bound parameters inside a function

I am using PDO to connect to MySQL, and I have an issue as follows : Given that code

$stmt = $conn->prepare($query);
$stmt->bindParam(':param0', $params[0]);
$stmt->bindParam(':param1', $params[1]);
$stmt->bindParam(':param2', $params[2]);

Then, I want to call a function foo($stmt,…), How can I use the array $params inside that function which would assign new values for each element of the $params array?

Advertisement

Answer

You will need to pass the $params array to the function by reference, since the parameters are bound to references to the caller’s array.

function foo($stmt, &$params) {
    $params[0] = 1;
    $params[1] = "abc";
    $params[2] = "xxx";
    $stmt->execute();
}

$stmt = $conn->prepare($query);
$stmt->bindParam(':param0', $params[0]);
$stmt->bindParam(':param1', $params[1]);
$stmt->bindParam(':param2', $params[2]);
foo($stmt, $params);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement