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); ?-->.
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 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](https://stackoverflow.com/questions/279170/utf-8-all-the-way-through/279279). – CD001 Jul 03 '19 at 08:28
  • it's the default charset xD I was to busy to fix that so I used the PHP utf8_encode xD –  Jul 03 '19 at 08:37

1 Answers1

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

Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345