kael.shipman Posted June 28, 2007 Share Posted June 28, 2007 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 More sharing options...
btherl Posted June 29, 2007 Share Posted June 29, 2007 Is vsprintf suitable? http://sg.php.net/manual/en/function.vsprintf.php Link to comment https://forums.phpfreaks.com/topic/57635-sprintf-variable-arguments/#findComment-285386 Share on other sites More sharing options...
corbin Posted June 29, 2007 Share Posted June 29, 2007 Whoa... I never know about vsprintf.... I could've used that a lot haha. Link to comment https://forums.phpfreaks.com/topic/57635-sprintf-variable-arguments/#findComment-285388 Share on other sites More sharing options...
kael.shipman Posted June 29, 2007 Author Share Posted June 29, 2007 Holy crap, that's perfect; thanks! I don't know how I've missed that for three years. -kael Link to comment https://forums.phpfreaks.com/topic/57635-sprintf-variable-arguments/#findComment-285973 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.