Page 1 of 1

Proper use of str_replace

Posted: Wed May 05, 2010 7:09 pm
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

Re: Proper use of str_replace

Posted: Wed May 05, 2010 8:33 pm
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]";
?

Re: Proper use of str_replace

Posted: Wed May 05, 2010 8:46 pm
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;

Re: Proper use of str_replace

Posted: Wed May 05, 2010 10:25 pm
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.