Hommer Smith
Hommer Smith

Reputation: 27852

Single quote with variable value in a double quote string

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.

Upvotes: 1

Views: 1485

Answers (4)

Nick
Nick

Reputation: 111

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.

Upvotes: 0

Hieu Le
Hieu Le

Reputation: 8415

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

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

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173562

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);

Upvotes: 3

Manse
Manse

Reputation: 38147

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)

Upvotes: 0

Related Questions