1

I would like to replace the placeholders used in a prepared statement with the elements of an array.

Let's say i have this sql string:

SELECT * FROM table WHERE col1 = ? AND col2 = ?

And an array like this:

$array = array(0=>'value1', 1=>'value2')

My output should be:

SELECT * FROM table WHERE col1 = value1 AND col2 = value2

I read that is possible to use an array as parameter for the PHP function str_replace, so my attempt so far is:

function debugQuery($sql,$param){
    return $ret = str_replace('?', $param, $sql);
}

This function instead of my desired output return:

SELECT * FROM table WHERE col1 = Array AND col2 = Array

I think i'm missing something...

M1L0
  • 71
  • 9
  • 2
    Perhaps you should use the [PDO Prepared Statements](http://php.net/manual/en/pdo.prepared-statements.php) specifically provided by PHP. Your solution is still open to [SQL Injection](http://bobby-tables.com/). – R. Chappell Nov 23 '16 at 16:22
  • I'm not trying to execute the statement after replace, it's just for debug reasons. I'would like to print a query that i can execute in phpMyAdmin. Thanks for the spot anyway! – M1L0 Nov 23 '16 at 16:24
  • 1
    The problem is, PHP doesn't do the preparing of the statement, the database does. You should use the [debugDumpParams](http://php.net/manual/en/pdostatement.debugdumpparams.php) command to see what it contains. – R. Chappell Nov 23 '16 at 16:30
  • 1
    In the comments this chap called Mark appears to have a function that does exactly what you want. http://php.net/manual/en/pdostatement.debugdumpparams.php#113400 – R. Chappell Nov 23 '16 at 16:33

1 Answers1

-2

Your code is (You will can remove mysql_real_escape_string, but this secure from sql-inj):

<?php
$sql = "SELECT * FROM table WHERE col1 = ? AND col2 = ?";
$array = array(0 => "TEST", 1 => "TEST2");
foreach ($array as $value) 
    $sql = preg_replace("#\?#", "'" . mysql_real_escape_string($value) . "'", $sql, 1);
echo $sql;
  • It works, anyway the output will not be execute on the DB. It's just for debug purpose. – M1L0 Nov 23 '16 at 18:18