[英]How to store a PHP variable in SQL such that when retrieved it is still a variable (not a value)
I want to save a string in SQL such that each time it is called, part of the string is a variable. 我想在SQL中保存一个字符串,这样每次调用它时,字符串的一部分就是一个变量。 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: 例如,如果字符串是“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中存储变量并保持变量?
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.