PHP: “… variables can be passed by reference” in str_replace()?

不问归期 提交于 2019-12-18 04:30:23

问题


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?


回答1:


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.




回答2:


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.




回答3:


I rewrite from VoteyDisciple

$sqlLogin = "SELECT * FROM users inner join role on users.roleId = role.id WHERE email=?1 and password=?2";
function makeSql() {
    $args = func_get_args();
    if(isset($args[1])) {
        $len = sizeof($args);
        //var_dump($args);
        $sql = $args[0];
        for ($index = 1; $index < $len; $index++) {
            $sql = str_replace('?'.strval($index), "'" . $args[$index] . "'", $sql);
        }
        return $sql;
    }
    return $args[0];
}
$sql = makeSql($sqlLogin, $myusername1, $mypassword);
$result = mysqli_query($con, $sql);


来源:https://stackoverflow.com/questions/5842366/php-variables-can-be-passed-by-reference-in-str-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!