Jump to content

sprintf variable arguments


kael.shipman

Recommended Posts

Hey everyone,

 

I've run into this problem a few times now and still haven't managed a decent solution.

 

I'm building an sprintf statement the arguments for which are either variable (i.e., dependent on certain environmental conditions) or bound together in one big string with separators. I've been handling it by using eval, but I figure there's got to be a better way than that.... Here's what I'm doing:

 

<?php
$query_extension = array();
$params = array();
if ($thisValue) {
$query_extension[] = "this_value = '%s'";
$params[] = 'thisRightValue';
}
if ($thatValue) {
$query_extension[] = "that_value = '%s'";
$params[] = 'thatRightValue';
}
if ($theOtherValue) {
$query_extension[] = "theOther = '%s'";
$params[] = 'theOtherRightValue';
}

if (count($query_extension)) {
$queryStatement = 'UPDATE `this_table` set `some_column` = 1 where '.implode(', ',$query_extension);

//Current method:
eval('$query = sprintf('.$queryStatement.', \''.implode('\', \'',$params).'\');');
//This sets $query equal to the output of
//sprintf("UPDATE `this_table` set `some_column` = 1 where this_value = '%s', that_value = '%s', theOther = '%s'", 'thisRightValue', 'thatRightValue', 'theOtherRightValue');

//Here's what I'd rather do:
$query = sprintf($queryStatement, /*use the PARAMS array to supply arguments*/);
}
?>

 

I know if I used sprintf for each of the individual parameters (like $query_extension[] = sprintf("this_value = '%s'",'thisRightValue')) that would work, but like I said, I've also got some parameters stored as strings:

 

<?php
$query = "UPDATE `this_table` set `some_column` = 1 where this_value = '%s', that_value = '%s', the_other_value = %d";
$arguments = 'thisRightValue*()*thatRightValue*()*2883';

$sql_query = sprintf($query,/*arguments without evaluating*/);
?>

 

Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/57635-sprintf-variable-arguments/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.