简体   繁体   中英

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. The PHP code will be commented out.

SQL stored Code:

Hallo und ein herzliches Willkommen auf der Homepage von <?php echo($p_name); ?>. <br>

Euer <?php echo($p_name); ?>.

PHP SQL Printer:

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

The answer is simple:

Don't Do That. Ever.

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:

Hallo und ein herzliches Willkommen auf der Homepage von

and then just use 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. Use a dedicated template engine like Twig and store templates in the filesystem, not database

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