简体   繁体   中英

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

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

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?

You could make it a format string for 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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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