Sven Kahn
Sven Kahn

Reputation: 497

Using if statements stored in mysql database

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

Answers (3)

Sam Graham
Sam Graham

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

Jijo John
Jijo John

Reputation: 1375

Store the If condion in your db as string. And then execute it using eval() php function .

usage

   mixed eval ( string $code )

PHP eval documentation

Upvotes: 0

nthall
nthall

Reputation: 2915

Sounds like you're looking for eval(), but note that it is especially dangerous to use if there's any chance someone besides you will be creating the strings. There is probably a better, safer way to achieve whatever it is you are trying to do here.

Upvotes: 1

Related Questions