PHP 用数组中的字符串替换字符

标签 php mysql

对于 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"

最佳答案

使用preg_replace_callback功能

$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/

相关文章:

php - 从数据库中选择(从今天)差异最小的日期

php - Google Charts & MySQL Timestamp 处理问题

php - Jquery ui 与 php/mysql 的问题

php - 如何修复完整性约束违规 : 1062 Duplicate entry '1-1' for key 'PRIMARY: Laravel Pivot Table

php - jQuery Mobile 的内部/外部链接问题

javascript - 在 JQuery 函数中回显 sql 查询

php - 从数组中选择每第 n 个项目

mysql - 存储全站用户事件的有效方式

MySQL , JOIN , 当总数 = 1

mysql - 自定义菜单保存在 Wordpress 3.0 数据库中的什么位置?