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

jbose2ul  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(441)

对于mysql,我使用以下格式:

  1. $sql = "select * from table where area_id = ? and item_id = ?";

然后准备并绑定参数等。如果查询失败,并且我记录$sql变量,那么我会得到上面的字符串,而这个字符串不是很有用。我想要的是带有中的绑定值的sql字符串。据我所知,没有简单的方法可以做到这一点,所以我想我可以这样做:

  1. sql_log(str_replace('?', array($area_id, $item_id), $sql));

要在我的日志中得到这样的内容:

  1. "select * from table where area_id = West and item_id = West" (spot the error!)

所以我知道我的错误是什么。但它不起作用。我明白了:

  1. "select * from table where area_id = Array and item_id = Array"
gopyfrb3

gopyfrb31#

拉威尔有个漂亮的助手。

  1. /**
  2. * Replace a given value in the string sequentially with an array.
  3. *
  4. * @param string $search
  5. * @param array $replace
  6. * @param string $subject
  7. * @return string
  8. */
  9. function replaceArray($search, array $replace, $subject)
  10. {
  11. $segments = explode($search, $subject);
  12. $result = array_shift($segments);
  13. foreach ($segments as $segment) {
  14. $result .= (array_shift($replace) ?? $search).$segment;
  15. }
  16. return $result;
  17. }
  18. $sql = 'SELECT * FROM tbl_name WHERE col_b = ? AND col_b = ?';
  19. $bindings = [
  20. 'col_a' => 'value_a',
  21. 'col_b' => 'value_b',
  22. ];
  23. echo replaceArray('?', $bindings, $sql);
  24. // SELECT * FROM tbl_name WHERE col_b = value_a AND col_b = value_b

来源:str::replacearray()

展开查看全部
irtuqstp

irtuqstp2#

使用preg\u replace\u回调函数

  1. $sql = "select * from table where area_id = ? and item_id = ?";
  2. $replace = array('area_id', 'item_id');
  3. echo preg_replace_callback('/\?/', function($x) use(&$replace) { return array_shift($replace);}, $sql);
  4. // select * from table where area_id = area_id and item_id = item_id
vx6bjr1n

vx6bjr1n3#

不幸的是, mysqli 没有一个好的方法来获取查询。可以使用方法替换参数:

  1. function populateSql ( string $sql, array $params ) : string {
  2. foreach($params as $value)
  3. $sql = preg_replace ( '[\?]' , "'" . $value . "'" , $sql, 1 );
  4. return $sql;
  5. }
bvpmtnay

bvpmtnay4#

试试这个:

  1. sprintf('select * from table where area_id = %s and item_id = %s', $area_id, $item_id);

  1. sprintf('select * from table where area_id = "%s" and item_id = "%s"', $area_id, $item_id);

如果数据库中的字段是整数%s,则必须将其替换为%d,并且不要使用引号

相关问题