Proper use of str_replace

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ZHarvey
Forum Newbie
Posts: 3
Joined: Wed May 05, 2010 7:03 pm

Proper use of str_replace

Post by ZHarvey »

Hi,

I have a MySql string that I am manually sanitizing/stripping and then parameterizing:

$sql = "SELECT * FROM widgets WHERE widget_id = ? and widget_is_superhuman = ?";

I have an array with the correct amount (in this case 2) of indices to match the number of question-mark-delimiters ("?"). For each index in this array, I want to string-replace the next subsequent ? with the value of the current array index.

Here's how I've set it up:

Code: Select all

for($i = 0; $i < sizeof($params); $i++)
    $sql = str_replace("?", $params[$i], $sql);
The problem is, this will replace *every* ? in the SQL string with the current array index's value; not one subsequent one at a time, like I need it to. I've searched the PHP docs high and low, and can't figure out how to use this function right.

Or, is there a sprintf()-like function in PHP that I should be using?

Thanks for all suggestions,
Z Harvey
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Proper use of str_replace

Post by califdon »

Yes, PHP has sprintf() function. Check it out at http://php.net/manual/en/function.sprintf.php. That's probably the simplest, although could you just write the string as:

Code: Select all

$sql = "SELECT * FROM widgets WHERE widget_id = ".$parametrs[0]." and widget_is_superhuman = ".$parameters[1]";
?
ZHarvey
Forum Newbie
Posts: 3
Joined: Wed May 05, 2010 7:03 pm

Re: Proper use of str_replace

Post by ZHarvey »

Hi,

thanks for the reply, but I can't do it the way you set it up.

You see, the $sql string is not going to be the example that I gave every time. It can be any arbitrary SQL query, with ?'s that need to be "swapped out" with filtered parameters. I have *a lot* of code depending on it working this way, so it's not something I can really change.

I basically need to know how to do this:

(1) Find the next ? in the string (if it exists)
(2) Swap it out with the next index of $params (an array constructed from other code)

Thus, a query string like:

"INSERT INTO widgets ( widget_height, widget_width ) VALUES ( ?, ? )"

Would turn into:

"INSERT INTO widgets ( widget_height, widget_width ) VALUES ( 300, 500 )"

...if my $params looked like:

$params[0] = 300;
$params[1] = 500;
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Proper use of str_replace

Post by requinix »

If you used

Code: Select all

INSERT INTO widgets ( widget_height, widget_width ) VALUES ( %d, %d )
instead you could easily give the query and parameters to sprintf.
Post Reply