如何在SQL中存储PHP变量,以便在检索时它仍然是变量(不是值)

时间:2021-02-11 14:02:04

I want to save a string in SQL such that each time it is called, part of the string is a variable. For example, if the string is "Hello my name is $name", I want to save it such that whenever it is retrieved, $name is still a variable:

我想在SQL中保存一个字符串,这样每次调用它时,字符串的一部分就是一个变量。例如,如果字符串是“Hello my name is $ name”,我想保存它,以便每当检索到它时,$ name仍然是一个变量:

$name = "Doug";
$row = mysql_fetch_array($mysql_query_result);

$message = $row['message'];  // "Hello, my name is $name."

echo $message;  // "Hello, my name is Doug."

One way would be:

一种方法是:

str_replace('$name', $name, $message);  // called before echo

I've never been too comfortable with variable variables, but from what I understand, a general function for the str_replace method could be made using them.

我对变量变量一直不太满意,但据我所知,str_replace方法的一般函数可以使用它们。

My question is whether or not this is necessary? Is there a much easier way to store a variable in SQL and keep it variable?

我的问题是这是否有必要?是否有更简单的方法在SQL中存储变量并保持变量?

3 个解决方案

#1


2  

You could make it a format string for sprintf.

你可以把它变成sprintf的格式字符串。

$name = "Doug";
$row = mysql_fetch_array($mysql_query_result);

$message = sprintf($row['message'], $name);  // "Hello, my name is %s."

echo $message;  // "Hello, my name is Doug."

Or str_replace as you said.

或者像你说的那样str_replace。

#2


1  

You could use eval() but I strongly suggest to not use it. Instead use a placeholder in your string and replace it when outputing, e.g. using sprintf() or str_replace() as you suggest.

您可以使用eval()但我强烈建议不要使用它。而是在字符串中使用占位符并在输出时替换它,例如如你所知使用sprintf()或str_replace()。

#3


0  

You could also do it at the query level using replace():

您也可以使用replace()在查询级别执行此操作:

//part of the query
$query .= "SELECT replace('message','\$name','{$name}')";

#1


2  

You could make it a format string for sprintf.

你可以把它变成sprintf的格式字符串。

$name = "Doug";
$row = mysql_fetch_array($mysql_query_result);

$message = sprintf($row['message'], $name);  // "Hello, my name is %s."

echo $message;  // "Hello, my name is Doug."

Or str_replace as you said.

或者像你说的那样str_replace。

#2


1  

You could use eval() but I strongly suggest to not use it. Instead use a placeholder in your string and replace it when outputing, e.g. using sprintf() or str_replace() as you suggest.

您可以使用eval()但我强烈建议不要使用它。而是在字符串中使用占位符并在输出时替换它,例如如你所知使用sprintf()或str_replace()。

#3


0  

You could also do it at the query level using replace():

您也可以使用replace()在查询级别执行此操作:

//part of the query
$query .= "SELECT replace('message','\$name','{$name}')";