1

I have a string that looks like this:

"count( IF (my_id = 'mykey',value,100)) mykey"

However, the value 'mykey' that goes right after my_id is in a variable called $which_value;

I fail to see how I can put the $which_value so that it mantains the single quote around it.

asked Jan 17, 2013 at 14:04
1
  • Do you mean something like "count( IF (my_id = '" . $which_value . "', value, 100)) mykey"? Commented Jan 17, 2013 at 14:06

4 Answers 4

3

Just add the variable inside your string:

"count( IF (my_id = '$which_value',value,100)) mykey"

You should, however, escape the value properly or use prepared statements:

$stmt = $db->prepare("SELECT count(IF (my_id = :my_value, value, 100)) mykey...");
$stmt->execute(array(
 ':my_value' => $which_value,
));

Or, using plain ol' mysql_ functions:

$sql = sprintf("SELECT count(IF(my_id = '%s', value, 100)) mykey...", 
 mysql_real_escape_string($which_value)
);
mysql_query($sql);
answered Jan 17, 2013 at 14:08
Sign up to request clarification or add additional context in comments.

1 Comment

Hope he use PDO to use the binding solution :)
0

To include a variable in a string you can do

"count( IF(my_id = '" . $which_value . "',value,100)) mykey"

Its quite hard to make out what exactly you are looking for but this should point you in the right direction (I hope)

answered Jan 17, 2013 at 14:06

Comments

0

You can always use your variable in a double-quoted string like this

"count( IF (my_id = '{$mykey}',value,100)) {$mykey}"
answered Jan 17, 2013 at 14:10

Comments

0

Inside of double quotes variables will be parsed. There is a convenient simple method just using the variable like this:

"count( IF (my_id = '$which_value',value,100)) mykey"

More complex expressions can be wrapped in curly braces like this:

"count( IF (my_id = '{$an_array[3]}',value,100)) mykey"

You may also want to consider escaping the variable string so that it does not break or open up to exploit, the string you are creating. If your id is an integer you can either typecast the variable as an integer:

"count( IF (my_id = '" . (int)$which_value . ',value,100)) mykey"

Or use the sprintf function to insert the variable into the string:

sprintf("count( IF (my_id = '%d',value,100)) mykey", $which_value)

If you need to escape text strings then you'll want to look at escape functions specific to the database you are constructing the query for.

answered Jan 17, 2013 at 14:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.