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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.