Jump to content

php content within a string


metazai

Recommended Posts

Quickie (I hope):

 

I have a line of PHP code that should only be written to an HTML file under certain conditions, and it pulls a variable from another piece of PHP:

 

$scriptquery = "SELECT * FROM scripts";

$scriptresult = mysql_query($scriptquery); 

while ($scriptrow = mysql_fetch_array($scriptresult)) {

     $replaceme="ooo!".$scriptrow['name']."!ooo";

     $replacescriptinclude="<?php $scriptquery = \"SELECT * FROM scripts WHERE name='".$scriptrow['name']."'\";$scriptresult = mysql_query($scriptquery);$scriptrow=mysql_fetch_object;echo($scriptrow->content); ?>";

     $txtContent=str_replace($replaceme,$replacescriptinclude,$txtContent);
}

 

Yet the money line, $replacescriptinclude, invariably writes this:

 

<?php SELECT * FROM scripts = "SELECT * FROM scripts WHERE name='randomquotes'";Resource id #3 = mysql_query(SELECT * FROM scripts);Array=mysql_fetch_object;echo(); ?>

 

Any ideas why?

Link to comment
https://forums.phpfreaks.com/topic/148939-php-content-within-a-string/
Share on other sites

inside double quotes, variables will be evaluated. if you don't want them evaluated, you need to escape them with a slash. also, you will need to escape other double quotes with a slash. the easiest way (in my opinion) is to use single quotes:

 

$replacescriptinclude='<?php 
$scriptquery = "SELECT * FROM scripts WHERE name=\'".$scriptrow[\'name\']."\'";
$scriptresult = mysql_query($scriptquery);
$scriptrow = mysql_fetch_object($scriptresult);
echo($scriptrow->content);
?>';

p.s. - i also fixed the mysql_fetch_object() function

 

you can also shorten the code to:

$replacescriptinclude='<?php 
$scriptrow = mysql_fetch_object(mysql_query("SELECT * FROM scripts WHERE name=\'".$scriptrow[\'name\']."\'"));
echo($scriptrow->content);
?>';

This was horribly messy code, I'm sorry, and only the result of too much time spent over-slaving on what I can now see was a terribly easy thing. It's like those damn 3-d dot pictures in reverse -- stare at something long enough and it becomes nothing.

 

Thanks for your help!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.