How to fetch data in multiple multidimensional array from mysql using codeigniter? - php

I am working on a report on which all employees and their salary detail will be fetch according to the departments wise. I have successfully fetch the employees by the department using multidimensional array but now I need to fetch the employees_salary_detail on that employees detail multidimensional array. It means first department->emp_detail->salarydetail. I have successfully fetch the first two part but now i am facing issue on fetching the last array in that emp_detail array.
public function getDepartmentReport(){
$employee = $this->db->select('*')
->from('departments')
->where('project_id', $this->session->userdata('client_id'))->get()->result_array();
$data = array();
foreach($employee as $m => $v){
$v['emp_detail'] = $this->db->select('first_name,employee_code,employees_salary.*')
->from('employees')
->join('employees_salary', 'employees_salary.employee_id = employees.id')
->where('employees.department_id',$v['id'])
->where('employees_salary.month', 'Nov')
->get()->result_array();
$data[] = $v;
foreach($v['emp_detail'] as $m => $s){
$s['salary_detail'] = $this->db->select('*')
->from('employees_salary_detail')->where('employees_salary_detail.salary_id', $s['id'])
->get()->result_array();
$data[] = $s;
}
}
return $data;
}
But now it is creating seperate array for showing salary detail not in that emp_detail array.
I don't know where i am making mistake. please help me to fix this issue.
THANK YOU IN ADVANCE FOR HELPING

Use Join Method to join all three tables in the database on the basis of common keys. I can see you have joined two tables same way you can join multiple tables and create a single array of data.
$qry = $this->db->query("SELECT * FROM product_section INNER
JOIN products ON product_section.ps_prid = products.prid INNER
JOIN wishlist ON wishlist.wish_product_id = products.product_id
INNER JOIN customer ON wishlist.wish_user_id = customer.cust_id
INNER JOIN brands ON brands.brand_id = products.product_brand
WHERE customer.cust_id = '$cid' GROUP BY
product_section.ps_prid");
like this above code

Related

PHP Query MySQL Tables from IDs from other tables

I have a database with several tables. I'm able to query IDs from a single table. What I'd like to do is Use those IDs to query another tables IDs, then use these new IDs to query fields from the final table. Here is what I am currently doing:
Here is how I acquire the first set of IDs:
$returnedPost = mysqli_query($con, "SELECT Region_ID FROM Region WHERE RegionName='" . $queryVar . "'");
function resultToArray($result) {
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
$rows = resultToArray($returnedPost);
//$rows[x]['Region_ID'];//returns Region_ID 1...n
I'd like to use the IDs in $rows to be able to query a new set of IDs from other tables as follows:
$newTbl = mysqli_query($con, "SELECT Location_ID FROM Location WHERE Region_ID=" . $rows[$x]['Region_ID']);
$rows2 = resultToArray($newTbl);
$finalTbl = mysqli_query($con, "SELECT Field1, Field2 FROM Posts WHERE Location_ID=" . $rows2[$x]['Location_ID']);
Can someone please tell me how I can accomplish this? Thanks.
you can use INNER JOIN in one query to get at this data, maybe something like this
SELECT P.Field1,P.Field2
FROM Region R
INNER JOIN Location L ON R.Region_ID = L.Region_ID
INNER JOIN Posts P ON L.Location_ID = P.Location_ID
WHERE R.RegionName = Your_Region_QueryVar

How do i merge specific parts of an associative array?

Question first, explanation later:
Insteat of the first array, i want one which looks like the secound array:
echo json_encode($movies);
//WHAT I DO NOT WANT: [{"movie_name":"test1","genre_name":"Action"},{"movie_name":"test2","genre_name":"Drama"},{"movie_name":"test2","genre_name":"Action"}]
//WHAT I WANT: [{"movie_name":"test1","genres":["Action"]},{"movie_name":"test2","genres":["Drama","Action"]}]
So insteat of severals rows with the same value for movie_name but different values for genre_name, i want one row for each movie, where all genre_names are merged into one gernes array;
The solution i wish:
The data is fetched from an database using php and mysqli. This is the SQL query i use and which generates the first array:
SELECT movies.movie_name, genres.genre_name FROM genres
INNER JOIN genre_movie ON genres.id = genre_movie.genre_id
INNER JOIN movies ON movies.id = genre_movie.movie_id;
I am not good with SQL and think there is a query which gets the me the secound array (the one I WANT) right away.
My solution so far:
i actually solved the problem using a php arglorithm, but its kinda complecated and hard if the anything scales or i add new columns:
foreach($myArray as $movie)
{
foreach($newList as $key => $item)
{
if($item['movie_name'] == $movie['movie_name']){
$exists = true;
$position = $key;
}
}
if($exists == true)
{
$newList[$position]['genres'][] = $movie['genre_name'];
$exists= false;
} else {
$newList[] = array('movie_name' => $movie['movie_name'], 'genres' => array($movie['genre_name']));
}
}
Take a look at group_concat: http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
I didn't emulate your tables but maybe this is your query:
SELECT movies.movie_name, group_concat(genres.genre_name) FROM genres
INNER JOIN genre_movie ON genres.id = genre_movie.genre_id
INNER JOIN movies ON movies.id = genre_movie.movie_id
GROUP BY movies.movie_name;
Edition
Well, I emulated it now, and yes, it's your query. I would just change:
group_concat(genres.genre_name)
For:
group_concat(distinct(genres.genre_name))
To return only different values.

Converting SQL query to codeigniter active record

I am working on a private message app using CodeIgniter.
I have 3 tables:
conversations
conversations_messages
conversations_members.
I am trying to join the tables by matching the conversations ids and fetch all the messages for the user who's logged in.
This is the standard sql query
SELECT
'conversations','conversation_id',
'conversations','conversation_subject',
MAX('conversations_messages','message_date') AS 'conversation_last_reply'
FROM 'conversations'
LEFT JOIN 'conversations_messages' ON 'conversations'.'conversation_id' = 'conversations_messages'.'conversation_id'
INNER JOIN 'conversations_members' ON 'conversations'.'conversation_id' = 'conversations_members'.'conversation_id'
WHERE 'conversations_members', 'user_id' = $sender_id
AND 'conversations_members','conversation_deleted' = 0
GROUP BY 'conversations'.'conversation_id'
ORDER BY 'conversation_last_reply' DESC";
Its a big query, hence; I'm not sure how to convert it to CodeIgniter active records or simply make it run with the framework.
Any corrections would be appreciated too.
Try below code with CodeIgniter active record.
$this->db->select('conversations, conversation_id, conversation_subject');
$this->db->select_max('conversations_messages.message_date', 'conversation_last_reply');
$this->db->from('conversations');
// Joining with conversations_messages table
$this->db->join('conversations_messages','conversations.id=conversations_messages.conversation_id','left');
$this->db->join('conversations_members','conversations.id= conversations_members.conversation_id','inner');
$this->db->where('conversations_members.user_id',$sender_id);
$this->db->where('conversations_members.conversation_deleted','0');
$this->db->group_by('conversations.conversation_id');
$this->db->order_by('conversation_last_reply');
// Get the results from db
$query = $this->db->get();
// Result array contains the records selected
$result_array = $query->result_array();
Happy coding
Naseem
$this->db->select('conversations, conversation_id, conversation_subject');
$this->db->select_max('conversations_messages.message_date', 'conversation_last_reply');
$this->db->from('conversations');
// Joining with conversations_messages table
$this->db->join('conversations_messages','conversations.id=conversations_messages.conversation_id','left');
$this->db->join('conversations_members','conversations.id= conversations_members.conversation_id','inner');
$this->db->where('conversations_members.user_id',$sender_id);
$this->db->where('conversations_members.conversation_deleted','0');
$this->db->group_by('conversations.conversation_id');
$this->db->order_by('conversation_last_reply');
// Get the results from db
$query = $this->db->get();
// Result array contains the records selected
$result_array = $query->result_array();

Nested associative array from DB fetch

i want to do the following but haven't found how to.
Or i'm not sure if there is a better way / practice, if you can point me that way i will appreciate it.
I have 2 tables on my DB
Table1 : Categories
Table2 : Subcategories
Table2 is associated with table1 by the primary key.
So for 1 row in the table1 i can have multiple associated rows on the table2.
I query and fetch the data on my Table1 like this:
$result = $mysqli->query("SELECT * FROM table1");
$post = array();
while ($row = $result->fetch_object()){
$row->sub = get_subcategories($row['id']); /* this value is added to the array since i want to store in here the associated arrays from the table2 */
$post[] = $row;
}
return $post;
Then i do the following query also on another function for the table2 data based on every id from the table1
function get_subcategories($id){
$result = $mysqli->query("SELECT * FROM table2 where categories_id = '$id'");
$post = array();
while ($row = $result->fetch_object()){
$post[] = $row;
}
return $post;
}
But the result im getting when using var_dump doesn't seem right.
Can i do it? or what am i doing wrong?
Thanks in advance
Use a single JOIN query:
$result = $mysqli->query("SELECT * FROM table1 t1 JOIN table2 t2 ON t2.categories_id = t1.id ORDER BY t1.id");
$posts = array();
while ($row = $result->fetch_object) {
if (!isset($posts[$row->categories_id])) {
$posts[$row->categories_id] = $row;
$posts[$row->categories_id]->sub = array();
}
$posts[$row->categories_id]->sub[] = $row;
}
This will create nested arrays. The first level will be an associative array whose keys are category IDs and values are objects. The objects will have a sub property that is an array of all the subcategories. Both the categories and subcategories are the objects returned by fetch_object, so there will be duplication. But you can just refer to the appropriate object properties for a particular level.

Inner join results in different arrays

I am using an inner join statement to retrieve data from both the tables Venues and Users. However, I would like to have an array looking like this
$resultsFromVenueTableArray = array(
$relevantVenueKey => $relevantVenueValue,
$resultsFromUserTable => $arrayOfValuesFromUserTable
);
rather than just one array full of all of the retrieved data looking something like this:
$resultsFromQuery = array(
$venueKey,
$userKey,
$venueKey...
)
How could I achieve this?
Here's my code;
$query = $this->db->query("SELECT * FROM Venues INNER JOIN Users ON Users.id = $userID", array($userID));
$venues = array();
foreach ($query->result() as $row) {
$row->username = $username;
$venues[] = $row;
}
It isn't clear from the question exactly what you would like to do, but you can pull out specific columns from both tables like so:
SELECT Venues.*, Users.username FROM Venues INNER JOIN Users ON...
which would allow you to pull out only the 'username' column from 'Users'.
A join is always going to leave you with an array of rows, if you need something else you'll probably have to manipulate the data once you've got it in PHP unless I've misunderstood your question.
Something like this would get you all venues by a user, with the username as the array key:
$venuesByUser = array();
foreach ($query->result() as $row) {
$venuesByUser[$row->username][] = $row;
}

Categories