Reputation: 878
I'm currently looking into classes, etc. I'd like to load something into my object from my database, like this:
$result = mysqli_query($link,"SELECT * FROM `recepten` WHERE `id` = $id LIMIT 1");
$obj = mysqli_fetch_object($result);
$this->id = $obj->id;
$this->titel = $obj->titel;
$this->ingredient = $obj->ingredient;
$this->beschrijving = $obj->beschrijving;
$this->van = $obj->van;
$this->tot = $obj->tot;
$this->altijd = $obj->altijd;
As you can see I'm loading $obj
directly into $this
. I'm guessing there must be a faster way to do this, I simply can't figure out how... Also google doesn't help.
Any thoughts?
Upvotes: 0
Views: 333
Reputation: 10975
I think the best method would be to define what columns you want, and by those columns, load it within your $this
. Note that if these are not defined within the class, they will be public properties within your class.
$columns = array('id', 'titel', 'ingredient', 'beschrijving', 'van', 'tot', 'altijd');
$selects = implode('`,`', $columns);
$result = mysqli_query($link, 'SELECT `'.$selects.'` FROM `recepten` WHERE `id` = '.$id.' LIMIT 1');
$obj = mysqli_fetch_object($result);
foreach ($columns as $column)
$this->{$column} = $obj->{$column};
Make sure that $columns
is not user input, as it is not escaped. You should also make sure $id
is safe as well.
Upvotes: 1