24Nov/100

PHP Stored In MySQL Database

Sometimes it’s helpful to store PHP code in a database and have it execute prior to displaying in the end user’s browser. This can easily be accomplished by using the PHP eval() function.

Assuming the MySQL table appears as follows:

+--------------+
|         code |
+--------------+
| Hello World! |
+--------------+

This can be displayed in the browser by using the following PHP code:

<?php echo $row_table['code']; ?>

Which will appear in the browser as follows: “Hello World!”

However, if the table contains mixed, PHP and HTML content, as follows:

+-----------------------------------------------------+
|                                                code |
+-----------------------------------------------------+
| <p>My PHP script: <?php echo 'Hello World'; ?>.</p> |
+-----------------------------------------------------+

This can be displayed by using the following PHP code:

<?php eval('?>'.$row_table['code'].'<?php '); ?>

The browser will display “My PHP script: Hello World.”

This essentially tells the web server to execute the PHP code between the PHP tags and print the output along with the rest of the string not between the PHP tags.

If however, the MySQL field is storing only PHP code as follows:

+------------------------------------+
|                               code |
+------------------------------------+
| echo 'Three plus five is: '.3 + 5; |
+------------------------------------+

The eval() function may be used as follows:

<?php eval($row_table['code']); ?>

The browser would display “Three plus five is: 8″

Tags: , ,

You must be logged in to post a comment.