Chilipepper
Chilipepper

Reputation: 182

Putting variable inside array[]

So instead of spending much time explaining i will just show you what the problem is, i have this method

public function lockCheck($string)
   {
        $Data = $this->getQuery("SELECT '$string' from settings where id=1");
        if ($Data->num_rows==1)
        {
            while($Row = $Data->fetch_assoc())
            {
                if ($Row[$string]==1)
                {
                    return true;
                }

                else 
                {
                    return false;
                }
            }
        }
   }

And its working perfectly fine if i dont have a parametar and just use 'locked' which is column from my table. But when i try using parametar $string it will always return false.

And this is how i call the method:

$ks->lockCheck("locked")

Any help will be appreciated.

Upvotes: 0

Views: 42

Answers (1)

vaso123
vaso123

Reputation: 12391

In your SQL, when you want to avoid to use a reserved keyword, you need to escape your variable wiht ` character, not single quote.

For example:

$Data = $this->getQuery("SELECT `".$string."` from settings where id=1");

This is also works, but previous I think is more elegant:

$Data = $this->getQuery("SELECT `$string` from settings where id=1");

Upvotes: 1

Related Questions