Reputation: 143
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"
Upvotes: 2
Views: 1659
Reputation: 4074
Laravel has a beautiful helper for just that.
/**
* Replace a given value in the string sequentially with an array.
*
* @param string $search
* @param array $replace
* @param string $subject
* @return string
*/
function replaceArray($search, array $replace, $subject)
{
$segments = explode($search, $subject);
$result = array_shift($segments);
foreach ($segments as $segment) {
$result .= (array_shift($replace) ?? $search).$segment;
}
return $result;
}
$sql = 'SELECT * FROM tbl_name WHERE col_b = ? AND col_b = ?';
$bindings = [
'col_a' => 'value_a',
'col_b' => 'value_b',
];
echo replaceArray('?', $bindings, $sql);
// SELECT * FROM tbl_name WHERE col_b = value_a AND col_b = value_b
Source: Str::replaceArray()
Upvotes: 0
Reputation: 21
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
Upvotes: 1
Reputation: 5097
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;
}
Upvotes: 2
Reputation: 26153
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
Upvotes: 3