Reputation: 497
I'm doing something where I need to store if statements in a mysql database. I need to pull these statements and use them, each one is an algorithm that I'm testing. I know you can store an if statement in a variable like "$abc = $x > 1 && $f == 1;" and if you run if($abc) {} it will work, I figured I could do the same here, but when I run if($abc) with $abc being an if statement from the database it's not working, it's running the code within the if statement because $abc exists. Code is as follows...
$getAlgorithms = mysqli_query($mysql_connect, "SELECT * FROM `algorithms2`");
while($algorithms = mysqli_fetch_array($getAlgorithms)) {
$algorithmID = $algorithms['id'];
$algorithm = $algorithms['algorithm'];
if($algorithm) {
echo("HELLO WORLD");
}
}
dummy example of what $algorithms['algorithm']; would pull: $r >= $var_x && $z <= $var_y && $lz >= $var_c
I'd really appreciate the help, this is very important. If you have any questions please ask.
NOTE: This is a 100% internal platform
Upvotes: 1
Views: 97
Reputation: 1621
Your code needs to make use of eval()
to work as-is:
$getAlgorithms = mysqli_query($mysql_connect, "SELECT * FROM `algorithms2`");
while($algorithms = mysqli_fetch_array($getAlgorithms)) {
$algorithmID = $algorithms['id'];
$algorithm = $algorithms['algorithm'];
if(eval("return {$algorithm};")) {
echo("HELLO WORLD");
}
}
However, executing arbitrary code from an external source (the database) is potentially a horrible security risk: just because you're expecting $algorithm
to be a benign arithmetic expression doesn't mean that it can't be a malicious function call or other statement, for example if someone can enter system('rm -rf /')
as the algorithm into your database, you're probably going to have a bad day.
Without knowing the precise problem you're trying to solve, it's hard to suggest a better solution, but I'd favour putting the "algorithms" in an array or other hard-coded data-structure within your code rather than the database, it's far safer as anyone who can alter that list can already execute arbitrary code.
For further reference: http://php.net/manual/en/function.eval.php
Upvotes: 1
Reputation: 1375
Store the If
condion in your db as string. And then execute it using eval()
php function .
usage
mixed eval ( string $code )
Upvotes: 0