The thing is, you have classes, and then you have database data. When you create an object, how do you set the properties of objects to store data in a database?
I saw something like this and I wonder if this is really the best way to do this. I am sure this is a fairly common problem, but I do not know what are the most acceptable solutions on how to handle it.
In this example, when the object is created, you pass the identifier as a parameter, and then run a query into the database with the identifier, and you return the return values ββto the properties of the object. I have little experience with PHP, and I have not seen this used a lot.
Is this an acceptable way to achieve this? Is there a better or more acceptable way?
public function __construct($id = null){ if($id != null){ $sql = "SELECT * FROM users WHERE user_id = $id"; $res = Db::returnRow($sql); // $res contains an associative array with database columns and values if($res){ $this->user_id = $res['user_id']; $this->user_name = $res['user_name']; //and so on... } } }
Can someone provide sample code or pseudo-code to illustrate how to do this correctly?
source share