Jump to content

Storing a variable name in a mysql table


Joesavage

Recommended Posts

Hello. I am trying to store a variable name in a mysql table... for instance...

 

Have the string "Hi The Variable is $Var1" stored in the table. Then on the php file...

 

<?php
$Var1 = Yay!
connect to mysql database.
select * from table blahblahblah
echo "$row[string]";
?>

and have that echo out "Hi The variable is Yay! I tried this and it prints out Hi The Variable is $Var1 instead, even tho I have set $Var1 to Yay!. Any ideas on how this can be done?

You would need to use the eval() function - http://us2.php.net/eval

 

However, this is dangerous and you would need to make sure that the content that is passed through the eval function is free of any dangerous code. Also, a syntax error in the code will cause the eval to fail.

 

The normal way to do this is to put a unique placeholder into the string where you want to replace a value at runtime and then do a string replace to put the actual value in. Something like -

 

"Hi The Variable is {Var1}"

 

Edit: Here is a generic preg_replace that will replace any number of {name1}, {name2}, ... placeholders in a string with the corresponding variable values - http://us3.php.net/manual/en/function.preg-replace.php#84979

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.