0

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= ?"

The second element is an array which contains an array of string values (in this case 1 and 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"

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

Here is the code

//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');

Thanks everyone!

2
  • "WHERE col1 = ? AND col2= ?" or perhaps "WHERE col1 = ? OR col2= ?"... but what does "WHERE col1 = ?, col2= ?" actually give you? Commented Mar 10, 2011 at 16:39
  • @Mark Baker That's probably a typo. Commented Mar 10, 2011 at 16:41

1 Answer 1

1

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.

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Awesome, that's precisely what I was looking for. Sorry, I'm a newbie to PHP!
@user653863 I'm glad I was helpful, but please tell me, which part was exactly what you needed? :)
I wasn't aware of the PDO prepare, execute format. This way, I can just pass in the second element of the array and have it automatically prepare and parse the statement.
@user653863 Exactly. You were trying to reinvent the wheel... and make it square.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.