简体   繁体   English

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

[英]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

You could use eval() but I strongly suggest to not use it. 您可以使用eval(),但我强烈建议不要使用它。 Instead use a placeholder in your string and replace it when outputing, eg using sprintf() or str_replace() as you suggest. 而是在字符串中使用占位符,并在输出时替换它,例如,按照您的建议使用sprintf()或str_replace()。

You could also do it at the query level using replace() : 您也可以使用replace()在查询级别执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM