I created a function to print a prepared-statement-sql-string with the variables in it, based on what I found in this other StackOverflow question.
Here is my code:
foreach($params as $idx => $param) { if ($idx == 0) continue; $sql = str_replace('?', "'" . $param . "'", $sql, 1); } printError($sql);
When I run this I get: Fatal error: Only variables can be passed by reference
for line 3. However when i use
$sql = preg_replace('/\?/', "'" . $param . "'", $sql, 1);
for line 3 it works fine.
Any idea why?
TL;DR: PHP supports both pass by value and pass by reference. References are declared using an ampersand ( & ); this is very similar to how C++ does it. When the formal parameter of a function is not declared with an ampersand (i.e., it's not a reference), everything is passed by value, including objects.
When the variable is passed as a reference then it is called pass variable by reference. Here, both the main variable and the passed variable share the same memory location and & is used for reference. So, if one variable changes then the other will also change.
The very last parameter, count, is passed by reference. You can see this in the description at http://us.php.net/str_replace where there's a &
in front of the variable.
This means you cannot use a literal 1
there. You'd have to do:
$sql = str_replace('?', "'" . $param . "'", $sql, $count); echo $count;
You'll now have displayed on the screen how many instances were replaced.
Look at the documentation for preg_replace
and str_replace
and you will see why. str_replace
's fourth argument must be passed by reference, but this is not the case for preg_replace
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With