PHP: "... variables can be passed by reference" in str_replace()? PHP: "... variables can be passed by reference" in str_replace()? php php

PHP: "... variables can be passed by reference" in str_replace()?


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.


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);