Konservin
Konservin

Reputation: 1017

store a reference to a variable in SQL table

How would it be possible to store a reference to a variable in SQL table? I have this code:

$id = 10;
$variable_value = 'real value';
$connect_db=mysqli_connect('localhost', 'this', 'that', 'a_table');
$result = $connect_db->query("SELECT * FROM the_table where id = '$id'");
$row = $result->fetch_assoc();
$the_function = $row['trigger']; // this row has a value '$variable_value' (w.o quotes)
echo '$the_function:'.$the_function.'<br>'; // echoes '$variable_value'

Is possible to have it echo 'real value' instead?

Upvotes: 0

Views: 85

Answers (2)

Digital Chris
Digital Chris

Reputation: 6202

You can use variable variables to double-evaluate what you have in your database value:

$the_function = "variable_value";

echo $$the_function;

outputs

real value

Note that you don't need to prepend your database value with a $, you'll only complicate matters.

Also the fact that you call it "the_function" makes me think you want to use this to call a function whose name is the variable... well you can also do this!

function variable_value() {
   echo "real value"; 
}
$the_function();

Here are both methods in action:

https://eval.in/92869

Upvotes: 1

AyB
AyB

Reputation: 11665

Try:

 $the_function = $row['trigger']; // this row has a value '$variable_value' (w.o quotes)
 $the_function = ltrim($the_function,'$');
 echo '$the_function:'.${$the_function}.'<br>'; 

It's called a variable variable name. Reference

For this to work the $ has to be removed. So I left-trim it out from your $the_function and use ${$<variable_name>} to reference it as a variable of its value.

Upvotes: 0

Related Questions