对于 mysql,我使用格式:
$sql = "select * from table where area_id = ? and item_id = ?";
然后准备并绑定(bind)参数等。如果查询失败并且我记录 $sql 变量,那么我将准确地得到上面的字符串,但它没有那么有用。我想要的是带有绑定(bind)值的 sql 字符串。据我了解,没有简单的方法可以做到这一点,所以我想我可以这样做:
sql_log(str_replace('?', array($area_id, $item_id), $sql));
要在我的日志中获取类似的内容:
"select * from table where area_id = West and item_id = West" (spot the error!)
所以我知道我的错误是什么。但这不起作用。我明白了:
"select * from table where area_id = Array and item_id = Array"
最佳答案
$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
关于PHP 用数组中的字符串替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52843269/