1

我有一个看起来像这样的字符串:

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

但是,紧随 my_id 之后的值“mykey”位于名为 $which_value 的变量中;

我看不到如何放置 $which_value 以便它在其周围保留单引号。

4

4 回答 4

3

只需在字符串中添加变量:

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

但是,您应该正确地转义该值或使用准备好的语句:

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

$stmt->execute(array(
    ':my_value' => $which_value,
));

或者,使用普通的 ol'mysql_函数:

$sql = sprintf("SELECT count(IF(my_id = '%s', value, 100)) mykey...", 
    mysql_real_escape_string($which_value)
);
mysql_query($sql);
于 2013-01-17T14:08:01.960 回答
0

要在字符串中包含变量,您可以这样做

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

很难弄清楚您到底在寻找什么,但这应该为您指明正确的方向(我希望)

于 2013-01-17T14:06:37.480 回答
0

您始终可以在这样的双引号字符串中使用您的变量

"count( IF (my_id = '{$mykey}',value,100)) {$mykey}"
于 2013-01-17T14:10:04.773 回答
0

双引号内的变量将被解析。有一个方便的简单方法,只需使用如下变量:

"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.

于 2013-01-17T14:24:16.317 回答