user656925
user656925

Reputation:

Eval Purpose | SQL transormation?

I store my sql queries as strings and then use them later in PDO as shown below.

There is one line that I don't understand:

eval("\$query = \"$query\";");

From the docs..eval should run a string as PHP code. Why can't I just use $query directly? What does it mean to run a string of SQL?

This code works. I just don't know what eval() statement is for.

Note this is safe eval() as the input is not user defined.

    "arc_id" =>                 "SELECT id FROM credentials WHERE email=?",
    "arc_id_from_hash" =>       "SELECT id FROM credentials WHERE pass=?",
    "signin_pass" =>            "SELECT pass FROM credentials WHERE email=?",
    "signin_validate" =>        "SELECT id, hash FROM credentials WHERE email=? AND pass=?"
);
public function __construct()  
{
    $this->db_one = parent::get();
}
public function _pdoQuery($fetchType, $queryType, $parameterArray=0) // needs review
{
    $query=$this->sql_array[$queryType];

    // what?

    eval("\$query = \"$query\";");

    // if not input parameters, no need to prep

    if($parameterArray==0)
    {
        $pdoStatement = $this->db_one->query($query);

Upvotes: 2

Views: 179

Answers (2)

gen_Eric
gen_Eric

Reputation: 227280

eval("\$query = \"$query\";");

This is a variable replacer/templating engine.

It is replacing variables inside $query with their values.

I suggest not using eval for this, it'd probably be better to use preg_replace or str_replace.

For reference, here's a question I asked: PHP eval $a="$a"?

Upvotes: 2

user166390
user166390

Reputation:

That code looks up the query by name, e.g. arch_id -> 'SELECT id ..', and then evaluates the query under a double-quote context in eval.

Presumable the queries could contain variables which would be interpolated. For instance, the original value might be 'SELECT id WHERE food = "$taste"' which would then then be evaluated as a double-quoted string literal in the eval and result in the interpolation of $taste so the result stored back in $query might then be 'SELECT id WHERE food = "yucky"'.

Given the data it appears to be "too clever" junk left over from a previous developer. Get rid of it. (If something similar is required in the future, although I would recommend strictly using placeholders, consider non-eval alternative mechanisms.)

Upvotes: 3

Related Questions