user10211847
user10211847

Reputation: 41

How do I use PHP code stored in a database and echoed in a new page?

I am a beginner in PHP, so I need a little help.

I have stored some PHP code in a MySQL database (in a table), and now I'm trying to echo in another PHP page (<?PHP echo $result['code'];?>) after making a successful connection with the database and selecting the right table where I stored the code in the code column. But it is not working.

If I store HTML or JavaScript or any code in the database and try to echo, the content is displayed as it was programmed, as you can see in this image:

So here is the image of view-sourcecode page where I'm trying to show that HTML or HTML CSS works perfectly, but in the case of PHP it shows the PHP in red colour and it does not work.

But it doesn't work with PHP. How can I fix it?

Upvotes: 0

Views: 268

Answers (1)

mtr.web
mtr.web

Reputation: 1515

I am going to have to do some guessing, and show a very simple example, but something like the following should work.

  1. Add a code_type column to your table with values of html, php, etc.

  2. Make sure that any php code stored in the database has been tested and returns some output (without using <?php tags). For example:

    $var1 = 100;
    $var2 = 10;
    $var3 = 1;
    
    echo "<h1> The equation of ($var1*$var2+$var3) equals</h1>";
    echo "<p>".($var1*$var2+$var3)."</p>";
    
  3. Use the code_type in your data-output script to either evaluate the PHP code or just echo it in all other cases:

    <?php
    if ($result['code_type'] == 'php') {
        eval($result['code']);
    } else {
        echo $result['code'];
    }
    ?>
    

I cannot say that I have ever used this, so I can't guarantee anything, but hopefully points you in the right direction.

Important:

It is worth noting that this is not considered good practice, as noted multiple times in the PHP Manual page. The manual itself notes it in several places, but the first comment is on-key:

If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP

... You are probably a lot better off parsing the php code before you save it to the database, then you won't have to worry about any of this!

Upvotes: 1

Related Questions