I am facing a problem that doesn't allow variables retrieved from cell data to appear as the declared variable on my web page. I will post an example below ;
email.db - Below represents the cell data for column email_body
email_body = Hi, $name
$name = $row['name'];
$messagebody = $row["email_body"];
$message = "
<html>
<body>
<p>".$messagebody."</p>
</body>
</html>
;
"
As you can see I'm attempting to make $row['name'] appear within $messagebody (which is text stored in a DB). The issue i'm having is that the above code will display $messagebody, but the $name variable will display as plain text and will ignore the variable.
Your help is appreciated,
Thanks.
Daniel - I think you might not have the exact right idea about how variables are rendered inside of PHP strings.
However, there is a function called sprintf
that might be the tool to do what you're attempting to do!
sprintf (string $format [, mixed $... ])
The first $format
argument in your case would be 'Hi, %s'
- the %s
being a stand-in for another string, $name
. The function would then return 'Hi, Bobby'
, were $name
set to bobby. (And name was passed as the second arg.)
// Re-set the data inside of `email_body` to 'Hi, %s';
// "%s" is a placeholder that hints that a string should be placed there
$name = $row['name'];
$messagebody = sprintf($row["email_body"], $name);
$message = "<html>
<body>
<p>".$messagebody."</p>
</body>
</html>";
You are attempting to evaluate PHP code in a string. That is generally unsafe. Instead of that, you can replace the placeholders (e.g. $name
) with the actual values.
Example:
$messagebody = "Hi, $name!"
$compiledmessagebody = preg_replace('/\$name/', 'Daniel V.', $messagebody);
$message = "
<html>
<head><title></title><head>
<body>
<p>".$compiledmessagebody."</p>
</body>
</html>
";
EDIT: actually, it would be better to use a templating engine to do the above and much more out of the box. Pug goes nicely with PHP https://www.phug-lang.com/
I would use HEREDOC syntax:
$name = $row['name'];
$messagebody = $row['email_body'];
$message = <<<HTML
<html>
<body>
<p>$messagebody</p>
</body>
</html>
HTML;
That way you don't have to worry about breaking out of strings and multi-line strings appear much neater.
Technically, you don't need to break out of a double quoted string when using a simple variable like you were doing.
With HEREDOC syntax the last HTML; needs to be pushed all the way to the left. In this case I am using HTML
as an identifier, but you can rename the identifier to something else.