Page 1 of 1

Store code in mysql?

Posted: Wed Jan 16, 2008 2:38 pm
by sierra467
I am wondering if it is possible to store php and HTML in a mysql database to be used in a PHP file.

What I am trying to do is to store "<a $attrib_list>\n\tTextLink\n</a>\n" in a mysql field named "syntax" database.

Then in a php file,
1) Create and populate the variable $attrib_list
2) Create a loop to pull out the syntax field data as specified above and assign it to $syntax below the variable $attribute_list
3) Use print statement to out the variable $syntax which I was hoping would be populated with the variables contents of $attrib_list.

So lets say this:

Code: Select all

$attrib_list = ' href="../index.html" title="index"';
...
while ($row = mysql_fetch_array($result)){
    $syntax = $row['syntax'];
}
...
print "<html>\n";
print "<head><title></title></head>\n";
print "<body>\n";
print $syntax;
print "</body>\n</html>\n";
I want the source code of the page in the browser to look like this:

Code: Select all

<html>
<head><title></title></head>
<body>
<a  href="../index.html" title="index">
    TextLink
</a>
</body>
</html>
Is it possible?

Re: Store code in mysql?

Posted: Wed Jan 16, 2008 3:07 pm
by John Cartwright
I would advise you to never store php code in the database.. that is just scary! However, yes it is possible by passing the string of php code through eval().

Re: Store code in mysql?

Posted: Wed Jan 16, 2008 3:31 pm
by sierra467
ok, thanks for the warning. I will try to dream up another way to do it. Thanks for the eval() heads up.

Re: Store code in mysql?

Posted: Thu Jan 17, 2008 11:38 am
by Kieran Huggins
sounds like a job for "view helpers" - little functions that build HTML in your template:

Code: Select all

function link_to($text,$url){
  return('<a href="'.$url.'">'.$text.'</a>');
}
You could get fancy by accepting an array of attributes as well, but I'll stop here.