JasonDavis
JasonDavis

Reputation: 48943

How can I store PHP code inside of a mysql table

I am working on building a small php/mysql script that will act something like a wordpress blog but will just be a small site for my eyes only to store PHP code snippets. So I will have categories and then pages with sample code that I write with a javascript syntax highlighter. Instead of storing my php code snippets in the file I am wanting to save them to mysql DB. So what is the best way to save PHP into mysql and to get it out of mysql to show on the page?

My end result will be something like this
alt text http://img2.pict.com/c1/c4/69/2516419/0/800/screenshot2b193.png


Update:

I just wasn't sure if I needed to do something special to the code before sending it to mysql since it has all different kinds of characters in it

Upvotes: 6

Views: 9578

Answers (6)

Richard G
Richard G

Reputation: 11

Try this:

mysql select ...

eval('?>' .  $row['phpcode'] . '<?php ');

Upvotes: 0

Yada
Yada

Reputation: 31225

Store as text (varchar) in the database.

Use cascading style sheet (css) to format code.

http://qbnz.com/highlighter/

Upvotes: 0

Asaph
Asaph

Reputation: 162801

Do you want to be able to search the php code? If so, I recommend using the MyISAM table type as it supports full text indexes (InnoDB does not). Your choices for column type when it comes to a fulltext index are char, varchar and text. I would go with text as your code snippets might get too long for the other types.

Another point worth mentioning, is make sure you properly escape all php code (or any value for that matter) before you insert it. The best way to do this is by using parameterized queries.

Upvotes: 2

JW.
JW.

Reputation: 51638

If you're not using some kind of database abstraction layer, just call mysql_real_escape_string on the text.

Upvotes: 4

Blank
Blank

Reputation: 7208

Unless I'm missing part of the problem, you should be safe storing it as a TEXT field in a MySQL database. Just make absolutely sure you sanitize the code snippets, as PHP code in particular is quite likely to contain the characters that will escape out of an SQL string. (If you're already using an SQL framework, odds are the framework is doing this for you.)

Upvotes: 0

Sampson
Sampson

Reputation: 268354

Just store in a text field, as is. Not much more beyond that.

Upvotes: 11

Related Questions