PHP用数组中的字符串替换字符 [英] PHP Replace character with string from an array
问题描述
对于mysql,我使用以下格式:
For mysql I use format:
$sql = "select * from table where area_id = ? and item_id = ?";
然后准备并绑定参数等.如果查询失败,并且我记录了$ sql变量,那么我会确切地得到上面的字符串,它的用处不大.我想要的是带有绑定值的sql字符串.据我了解,没有简单的方法可以执行此操作,因此我认为我可以执行以下操作:
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"
推荐答案
不幸的是,mysqli
没有一个很好的方法来获取查询.您可以使用一种方法来替换参数:
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;
}
这篇关于PHP用数组中的字符串替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!