0

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); ?-->.
2
  • 1
    As an aside: you're asking for trouble using latin1 in the database and utf-8 for output - you'd be better off just using UTF-8 all the way through. Commented Jul 3, 2019 at 8:28
  • it's the default charset xD I was to busy to fix that so I used the PHP utf8_encode xD Commented Jul 3, 2019 at 8:37

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.