[英]Printing HTML and PHP code out of SQL with PHP
I store HTML code that also contains PHP code in my database and I want to output it on my website. 我将还包含PHP代码的HTML代码存储在数据库中,并且希望将其输出到我的网站上。 The PHP code will be commented out.
PHP代码将被注释掉。
SQL stored Code: SQL存储代码:
Hallo und ein herzliches Willkommen auf der Homepage von <?php echo($p_name); ?>. <br>
Euer <?php echo($p_name); ?>.
PHP SQL Printer: PHP SQL打印机:
$query = "SELECT * FROM `news`";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
if (!empty($row)) {
echo(utf8_encode($row['content']));
}
Table Structure: 表结构:
CREATE TABLE `news` (
`entryid` int(11) NOT NULL,
`content` varchar(8000) CHARACTER SET latin1 COLLATE latin1_german2_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `news`
ADD PRIMARY KEY (`entryid`);
ALTER TABLE `news`
MODIFY `entryid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;
---RESAULT:--- ---结果:---
Hallo und ein herzliches Willkommen auf der Homepage von <!--?php echo($p_name); ?-->. <br>
Euer <!--?php echo($p_name); ?-->.
I store HTML code that also contains PHP code in my database and I want to output it on my website.
我将还包含PHP代码的HTML代码存储在数据库中,并且希望将其输出到我的网站上。
The answer is simple: 答案很简单:
It is not a good idea in general to store such dynamic HTML in the database, but if you have just a regular HTML with a few placeholders to output some data, then put some placeholders, not PHP code: 通常,在数据库中存储这样的动态HTML并不是一个好主意,但是,如果您只有一个带有几个占位符的常规HTML来输出一些数据,则放置一些占位符,而不是PHP代码:
Hallo und ein herzliches Willkommen auf der Homepage von
%p_name%
and then just use str_replace()
: 然后只需使用
str_replace()
:
echo str_replace("%p_name%", $p_name, $row['content']));
in case you want to store a full featured HTML template with loops, conditions, etc, it is possible but still not recommended. 如果您要存储具有循环,条件等功能的全功能HTML模板,则可以但仍然不建议这样做。 Use a dedicated template engine like Twig and store templates in the filesystem, not database
使用专用的模板引擎(例如Twig)并将模板存储在文件系统中,而不是数据库中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.