0

I am trying to set a function that will dynamically update an object attribute in the db w/o updating the whole object.

$sql = "UPDATE " . self::$table_name . " SET ";
$sql .= "$attribute = '" . eval("\$this->$attribute;") . "'";
$sql .= " WHERE ...";

I cant seem to get this eval("\$this->$attribute;") to produce the object attribute value. There is a value in the attribute and it is a public attribute.

Thanks

$attribute is a function var that will contain a string like 'address_id' so I want UPDATE table_name SET address_id = '11' WHERE user_id='1' This is a simple example of it

7
  • 8
    Why do you need to eval() it? Surely $this->attribute will suffice? Commented Feb 14, 2013 at 14:13
  • <cringe /> Why do you need to use eval in the first place? Why not simply use $this->attribute? Commented Feb 14, 2013 at 14:14
  • And learn to use Prepared statements Commented Feb 14, 2013 at 14:16
  • almost any time you use eval(), you're making a mistake. eval() is almost always unnecessary. It certainly doesn't seem necessary here. Commented Feb 14, 2013 at 14:27
  • $attribute is a function variable, tried '$this->attribute' didnt work. however I tried '$sql .= eval("return \$this->" . $attribute . ";");' and it worked. Commented Feb 14, 2013 at 14:29

2 Answers 2

2

You don't need to do this using eval. PHP supports variable variables: http://php.net/manual/en/language.variables.variable.php

So this will do:

$this->$attributes

Note the second $ sign. This basicly means the value of $attributes is used as attribute name. If you want it to write a bit clearer you can do so using brackets:

$this->{$attributes}

This bracket is required if you wanted to do this using an array, or if you wanted to use multiple variables to build a variable name like this:

$this->{$var1}_{$array[0]}_{$var2}

This goes probably behind the scope of this question, but its good to know what variable variables are. But i don't recommend using them, because it makes the code unreadable and hard to understand.

Sign up to request clarification or add additional context in comments.

Comments

1

There's no need to use eval():

$sql = "UPDATE " . self::$table_name . " SET ";
$sql .= "$attribute = '" . $this->attribute . "'";
$sql .= " WHERE ...";

If attribute is a variable, use:

$this->$attribute

Are you sure $this->attribute is sanitized correctly?

7 Comments

I think it should be like this '".$this->attribute."'
Not if it's a variable variable.
you forgot the first dot . for the concatination
Then the above should be fine.
@BasicBridge BenM didn't get the concatination issue, i did, so i wrote it again so he understands what you meant.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.