PHP 和 MySQL - 用数组中的 N 个值替换 N 个分隔符 [英] PHP and MySQL -Replacing N delimeters with N values from an array

查看:45
本文介绍了PHP 和 MySQL - 用数组中的 N 个值替换 N 个分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读一本关于设计模式的 PHP 书籍,并希望将他们的一个数据库模式合并到我的代码中.具体来说,类方法返回一个包含两个元素的数组.

I've been reading a PHP book on design patterns and would like to incorporate one of their database patterns in my code. Specifically,the class method returns an an array with two elements within it.

第一个元素是一个像这样的字符串.

The first element is a string looks like this.

"SELECT col1, col2, col3 FROM table WHERE col1 = ?, col2= ?"

第二个元素是一个数组,其中包含一个字符串值数组(在本例中为 1 和 2)

我正在寻找最有效的方法(它会经常用于实例化对象)在?"上合并这两个数组.分隔符,以便最终结果是一个字符串,它 ="SELECT col1, col2, col3 FROM table WHERE col1=1, col2=2"

I am looking for the most efficient way(it will be used quite often to instantiate objects) to merge these two arrays on the "?" delimiter so that the end result is a string which = "SELECT col1, col2, col3 FROM table WHERE col1=1, col2=2"

我见过诸如 preg_replace 之类的东西,但这依赖于固定的 N 个模式数组.我正在寻找更有活力的东西.我将在 PDO 选择语句中使用代码的输出.请注意,以上是一个特定示例,但我需要它为任意数量的 ?和输入

I've seen stuff such as preg_replace, but that relies on a fixed N array of patterns. I'm looking for something a little more dynamic. I will use the output of the code in a PDO select statement. Note that the above is a specific example, but that I need it to work for arbitrary amount of ? and inputs

这是代码

//This function returns an array of two elements, $string_ar[0] is the string, $string_ar[1] are the values
$string_ar = $selectionFactory->doNewSelection($friend_idobj,'has_friend');

谢谢大家!

推荐答案

首先我想通知你关于 PHP 的 PDO 扩展,它支持并专注于准备好的语句,甚至可以为不支持它们的数据库引擎模拟它们.

First of all I would like to inform you about PHP's PDO extension that has support for, and it's focused on, prepared statements and even emulates them for database engines that do not support them.

其次,如果你想在没有准备好的语句的情况下处理这个,你应该看看 strtok,甚至 explode 都可以这样做,如果你没有一个非常复杂的逻辑.

Secondly, if you want to handle this without prepared statements, you should take a look into strtok, or even explode may do it if you don't have a very complex logic.

这篇关于PHP 和 MySQL - 用数组中的 N 个值替换 N 个分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆