user10577559
user10577559

Reputation:

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); ?-->.

Upvotes: 0

Views: 57

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157981

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 %p_name%

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

Upvotes: 2

Related Questions