For mysql I use format:
$sql = "select * from table where area_id = ? and item_id = ?";
Then prepare and bind the parameters etc. If the query fails and I log the $sql variable then I get exactly the string above which isn't that useful. What I want is the sql string with the bound values in. As I understand it there is no easy way to do this so I am thinking I can do something like:
sql_log(str_replace('?', array($area_id, $item_id), $sql));
To get something like this in my log:
"select * from table where area_id = West and item_id = West" (spot the error!)
So I know what my error is. But it doesn't work. I get this:
"select * from table where area_id = Array and item_id = Array"
Use preg_replace_callback function
$sql = "select * from table where area_id = ? and item_id = ?";
$replace = array('area_id', 'item_id');
echo preg_replace_callback('/\?/', function($x) use(&$replace) { return array_shift($replace);}, $sql);
// select * from table where area_id = area_id and item_id = item_id
Unfortunately, mysqli
does not have a good way to get just the query. You could use a method to do the replacement of your parameters:
function populateSql ( string $sql, array $params ) : string {
foreach($params as $value)
$sql = preg_replace ( '[\?]' , "'" . $value . "'" , $sql, 1 );
return $sql;
}
try with this:
sprintf('select * from table where area_id = %s and item_id = %s', $area_id, $item_id);
or
sprintf('select * from table where area_id = "%s" and item_id = "%s"', $area_id, $item_id);
if your fields in the database are integers the %s you have to replace it with %d and do not use quotes