pg-robban
pg-robban

Reputation: 1435

Echo html+php from database

I am working on a site which deals with a lot of texts in HTML, so recently I learned PHP and moved them into a MySQL database and echo the contents given a specific chapter and section. Now this works relatively fine, the HTML shows up properly. However, in some parts I have included PHP function calls, and these doesn't seem to be evaluated - rather, they get just inserted into the source code (and thus invisible for the page viewer), never doing anything. They did work when they were simple .html files.

How can I solve this?

For example, a text can look like this:

<?php printChapterName(); ?>
<p>Some text</p>
...
<?php showImage($name, $alt-text); ?>
...

This just shows the text on the page.

Edit: The functions are echo:ing some HTML.

Upvotes: 1

Views: 2579

Answers (3)

dev-null-dweller
dev-null-dweller

Reputation: 29462

This one should do what you want: (function evalInlinePHP and using it in preg_replace_callback)

 $text = "<?php printChapterName(); ?> <p>Lorem ipsum</p>";
 function printChapterName(){ echo '<h1>Chapter #1</h1>'; }

 function evalInlinePHP($m)
 {
  ob_start();
  eval($m[1]);
  return ob_get_clean();
 }

 echo preg_replace_callback("/<\?php(.*)\?>/", 'evalInlinePHP', $text);
 //prints <h1>Chapter #1</h1> <p>Lorem ipsum</p>

But please note that it is not a good very bad idea to store php function in DB and then evaluate it. You should really rethink how to store and display these texts

Upvotes: 2

Lotus Notes
Lotus Notes

Reputation: 6363

Use eval() so that PHP evaluates the code coming from your database. Note that this is inherently dangerous unless you're the only person who's in charge of that PHP code. Also make sure that those functions are defined in your current page.

Upvotes: 1

nico
nico

Reputation: 51640

Well, you're echoing those calls, that's why they get written and not interpreted.

I reckon you should rethink the way you're saving your text in the database. Why using showimage($name) when you can simply store an <img> tag? If the images go in the same places in all the pages (e.g. if you have an image associated to each page), make another column with the img src in your table and output the image in its place with another PHP call.

For instance, something on the lines of (this is a rough example, but you get the idea):

$res = mysql_query("SELECT text, image FROM contents WHERE id_pag = ".$id);
$row = mysql_fetch_array($res);
// Output the image
echo '<img src="'.$row['image'].'" />'. $row['text'];

Upvotes: 1

Related Questions