简体   繁体   中英

How to output a php variable from a mysql database?

There is a variable $name in mysql table. This variable contains the name of the site.

How should I display it so that the value of this variable is displayed? When I try to output, the variable is displayed as plain text.

If I try to enclose it in braces as an alternative output, it produces an error:

Notice: Undefined variable.

Here is my code:

$db=mysqli_connect('127.0.0.1', 'root', '', 'demo');
mysqli_query($db, "SET NAMES 'utf8'");
$tb_var=mysqli_query($db, "SELECT * FROM var");
$var=mysqli_fetch_assoc($tb_var);
echo ${$var['name']};

Mysql code:

INSERT INTO `var` (`id`, `name`) VALUES (NULL, 'My site name $name');

You don't have just a variable. You have text that you expect to be handled as a PHP double-quoted string literal, which is close enough to evaluating external input as code to be worried.

You may want to switch to good old ...printf() format codes:

INSERT INTO `var` (`id`, `name`) VALUES (NULL, 'My site name %s');
printf($var['name'], 'Acme Corporate Site');

And, if in HTML context:

echo htmlspecialchars(sprintf($var['name'], 'Acme Corporate Site'));

Online demo

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