简体   繁体   中英

Querying database from php

I have a following structure of my database:

在此处输入图片说明

And I have created a class User within php which has following attributes:

public $user_id;
public $first_name;
public $last_name;
public $password;
public $job;
public $department;

Then in my code, I plan to have $job and $department to be objects called Job and Department.

Within a user class, I have method called load user data. I get all user data first but then I struggled how should I do my queries to get information for department and job(by id) should I have one query(using joints) to load all the data and create my object from that data, or should I run queries for Job and Department like that

    $this->department = new Department($this->dbc, $userData['department_id']);
    $this->job = new Job($this->dbc, $userData['job_id']);

Where within each of the object, query is executed and retrieves the data?

If you want to have Job and Department be an object, you are looking at using either method. If you choose to use joins in your SQL query, you will be working on just one object, containing the entire result set of your SQL query meaning you will only need to open and close one connection. If you choose not to use the joins, you would be returning your id fields to then query the Job and Department tables, opening and closing at least two more connections.

Personally, I would use one query, return one array to be kept in memory and then have your Job and Department objects just pull from that array. It keeps the number of connections down and your processing requirements lower.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM