0

I have a challenge that I have a hard time describing it in a short web search. I'm hoping if I can successfully explain it long form all the experts here can understand what I'm asking and let me know if this is even possible. This is theoretical/academic question, not a troubleshooting question.

Say I have a string in a SQL Table that looks like this:

"Hi my name is $name, very please to meet you!"

In my PHP code I have a variable $name with a value in it. If I manually copy this string into my PHP code, interpolation works as advertised and all is good. But if my script uses mysqli to fetch this string I end up with a string that doesn't interpolate, which I guess sort of makes sense, maybe. My question is, is there a way to force that string to interpolate?

I tried to parse out the variable name, in which case I ended with $varname="$name" and whenever I tried to print $varname I always got $name, not the value of $name. Am I barking up the wrong tree here, is this even possible? Should I be looking for an different ways to accomplish this, like store this string in two parts "Hi my name is " in one table field and ", very please to meet you!" in a different table field and then concatenate all three strings together like:

print "$dbstring1 . $name . $dbstring2";

Naturally this isn't the actual string I'm working with, just trying to keep things simple as this is more of a theoretical/academic question than a troubleshooting question.

6
  • I would consider using sprintf() and storing a template in the db like "Hi my name is %s." Edit to add: this would also let you change the order of the items that are filled in (for instance if you supported multiple languages). Commented Jul 5, 2022 at 23:41
  • From the duplicate, see the accepted answer Commented Jul 5, 2022 at 23:51
  • I'm not sure if the proposed "duplicate" answer fully answers this question. If you write a string in double quotes in PHP, it will process those variables. However, if you load an existing string (i.e. from database), it won't. You can use sprintf() if you don't need "named" parameters, alternatively have a look at this question: stackoverflow.com/questions/5701985/… Commented Jul 6, 2022 at 2:05
  • Regardless of which method you use, you will end up writing parameters in a specific format when storing the string, then processing it when retrieving. If using sprintf, you would use something like "Hi my name is %s, very please to meet you!". If using an alternate method, it might look like: "Hi my name is :name:, very please to meet you!" Commented Jul 6, 2022 at 2:07
  • I must have failed at explaining what I was trying to do as these solutions aren't even in the right ball park. Commented Jul 9, 2022 at 11:34

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.