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?

Community
  • 1
  • 1
Dexter
  • 3,072
  • 5
  • 31
  • 32

3 Answers3

42

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.

VoteyDisciple
  • 37,319
  • 5
  • 97
  • 97
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.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • 2
    This is _also the case for `$count` with `preg_replace`_, but the `$count` parameter for `preg_replace` is fifth, not fourth. The OP was using `$limit` with `preg_replace`, which does something else. – Lightness Races in Orbit Apr 30 '11 at 14:33
0

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);
nobjta_9x_tq
  • 1,205
  • 14
  • 16