开发者

Custom object based on database table

开发者 https://www.devze.com 2023-01-02 23:46 出处:网络
Suppose that I have a database query which looks like below - select name, gender, birthday from person where person_id = 1;

Suppose that I have a database query which looks like below -

select name, gender, birthday from person where person_id = 1;

When this query is executed, some records from the database is returned. I want to execute this query inside a function, then make a custom object which will contain the exact attributes as the column names, with the corresponding values. As an example, suppose that the object is X. So it will have three attributes which are X->name, X->gender and X->birthday, with the corresponding values from the records.

As a second example, consider the following query -

select test1, test2, test3 from test where test_id = 1;

I want to execute this query inside the same function and using the same method, then generate a custom-object Y which will contain the attributes Y->test1开发者_StackOverflow中文版, Y->test2 and Y->test3.

Is it doable in PHP? If so, then how?

Edit: By custom object, I meant any kind of object. It does not need to be an instance of a specific class or something like that. I just want to return an object from that function so that I can populate the appropriate classes from the returned object's property values.


foreach ($result as $key => $value)
{
    $your_object->{$key} = $value;
}


EDIT: this answer assumed Archangel used MySQL, which it turns out is not the case. Sorry for the mistake! I'll leave my answer here in case any MySQL folks come across it, as well as to preserve the comments if necessary.

If you don't care about custom classes and only want your custom attribute names in the row objects, this is all you need:

$row_object = mysql_fetch_object($result);

Otherwise, you'll need to write your own class yourself (I'm not sure whether a constructor is needed or the function populates your object with data automatically):

class X
{
    public $name;
    public $gender;
    public $birthday;
}

Then call the function like this:

$row_object = mysql_fetch_object($result, 'X');

There's no built-in way that I know of to generate classes on-the-fly for you; you'll have to write your own classes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号