i've this client who has a employee list and he wants to display all employees of same category(in group), i'm sorry if i'm not able to explain, i will try to explain
----------------------------
id | e_id | e_pos | e_name
-----------------------------
1 | 142 | dev | abc
2 | 143 | sr.dev | bac
3 | 144 | intern | jlk
4 | 145 | dev | jlsd
5 | 146 | dev | asdf
6 | 147 | sr.dev | adsc
7 | 148 | intern | mlkn
8 | 149 | sr.dev | vjll
9 | 150 | dev | knmk
10 | 151 | dev | jlkm
----------------------------
how to show the output
Number of dev(5)
1) abc
2) jlsd
3) asdf
4) knmk
5) jlkm
Number of intern(2)
1) jlk
2) mlkn
Number of sr.dev(3)
1) bac
2) adsc
3) vjll
now the problem is i've tried this piece of code
$this->db->select('e_id,e_pos,e_name');
$this->db->group_by('e_pos');
$query = $this->db->get('emp'); // table name
if($query->num_rows() > 0)
{
return $query->result();
}
but the above code is not working, it's just showing dev and number of dev, i want to see all dev data.
dev
I'm using Codeigniter 2.2.0
You can use this CI code to get your data (detailed docs on this link):
$query = $this->db->query("YOUR QUERY");
and then pass in following query:
select test.e_pos, test.e_name, inn.cnt
from test
inner join
(SELECT e_pos, e_name, count(e_pos) as 'cnt'
FROM `test`
group by e_pos ) inn on test.e_pos = inn.e_pos
order by test.e_pos
You will get table like this, which you can then iterate to display result:
foreach ($query->result() as $row)
{
// echo data as desired
}
Related
I have a table in the database like this:
student_id | subject_id | get_ca1 | get_ca2 | get_exam
----------------------------------------------------------
101 | 1 | 10 | 7 | 10
102 | 2 | 5 | 5 | 10
103 | 1 | 9 | 10 | 4
101 | 1 | 8 | 10 | 10
103 | 2 | 2 | 10 | 10
104 | 1 | 7 | 8 | 5
101 | 2 | 7 | 8 | 5
I want to get the highest score of a student in a subject. But first, I would have to sum up the rows get_ca1 + get_ca2....+ get_exam to another column to get the total scores of each student in a particular subject.
Then I want to get the Max score from the total. This means;
the highest score in subject_id = 1 is 28 gotten by student_id=101
the highest score in subject_id = 2 is 22 by student_id = 103
So far, this is my query:
SELECT MAX(`get_ca1`+`get_ca2`+`get_exam`)
AS max_score
FROM exam_results WHERE `subject_id`=1
This outputs 28.
Now, this is how I want my table in view to look:
For student_id= 103
subject | ca1 | ca2 | exam | highest
----------------------------------------
Maths | 9 | 10 | 4 | 28
Eng | 2 | 10 | 10 | 22
This is where my problem lies. I tried putting the code directly in the view file like this:
<td>
<?php
$query = $this->db->query("SELECT MAX(`get_ca1`+`get_ca2`+`get_exam`)
AS max_score FROM exam_results WHERE `subjects.id`=1");
$highscore = $query->row();
echo $highscore->max_score;
?>
</td>
It outputs 28 correctly. However, it shows 28 in all the subjects. I'm guessing is because of this WHERE `subjects.id`=1"
If I'm to go by this method, how do I get the highest scores to show in each subject column?
is it WHERE `subjects.id`=.'"$subject_id"`"?
But I would prefer the MVC method which I'm not so familiar with.
so far...
Model
public function GetMaxScore($subject_id)
{
$this->db->select_max('`get_ca1`+`get_ca2`+`get_exam` AS max_score');
$this->db->where('subject_id', $subject_id);
return $this->db->get('max_score')->row();
}
Controller:
public function GetMaxScore($subject_id)
{
$data = $this->examgroupstudent_model->GetMaxScore($subject_id);
return $data->max_score;
}
If this is correct by any means, how do I output it in my view?
I have built a membership application that allows users to assemble projects whose contents are contained across 2 tables ('projects' and 'notes'). Each member can create, update or delete as many projects as they want.
Good so far...
I'd like the members to be able to share their projects with other members they choose. At this point I have built a function that allows Member A to type in an email address in order to share a project (with say, Member B). If that email exists in the DB it updates a third table 'sharing' with the project owner's ID (Member A), the "shared_with" member's ID (Member B) and the project ID. (Perhaps I have gone bullheaded in the wrong direction?)
The problem: How do I query the DB to show Member B all of their own projects + any projects that have been shared with them? The query below illustrates the direction I've been which has been useless. I am trying to say, "Select all from projects where user_id = (me) AND all corresponding projects where my ID is in the 'sharing' table under the 'shared_with' column. ...Oh yeah, and grab that project_id in order to know which project while you're at it."
My brain is mush. Any direction would be sincerely appreciated.
function find_all_projects($id) {
global $db;
$sql = "
SELECT *
FROM projects
LEFT
JOIN sharing
on projects.id = sharing.project_id
WHERE user_id = '" . db_escape($db, $id) . "'
OR sharing.shared_with = '" . db_escape($db, $id) . "'
ORDER
BY project_name
";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;
}
Current Table Structure
From your question I believe your current table structure to be something like the following:
TABLE: user TABLE: project TABLE: shared
id | email | | id | user_id | content | | id | user_id | project_id
---+-------------------- ---+---------+------------------------------ ---+---------+------------
1 | james#website.com | | 1 | 1 | Project for James | | 9 | 1 | 5
2 | hannah#website.com | | 2 | 1 | Some other project for James | | 10 | 3 | 5
3 | lucy#website.com | | 3 | 2 | Project for Hannah | | 11 | 1 | 8
| | | 4 | 2 | A new project for hannah | | 12 | 2 | 8
| | | 5 | 2 | Hannah's pride and Joy | |
| | | 6 | 3 | Lucy cracking down | |
| | | 7 | 3 | Lucy's second project | |
| | | 8 | 3 | Lucy's public stuff | |
SQL
Example: https://www.db-fiddle.com/f/6KnEsGUmy5PS42usmzyTEX/0
SELECT project.id, project.user_id AS owner_id, shared.user_id AS shared_id, project.content
FROM project
LEFT JOIN shared
ON project.id = shared.project_id
AND project.user_id <> ?
WHERE project.user_id = ?
OR shared.user_id = ?;
N.B.
The key difference between this SQL statement and the one in your question is
AND project.user_id <> ?
Without that condition in the ON clause you will get duplicate records for every shared project for that user. I.e. if the user has shared the project with 20 users then there will be 20 duplicates.
This is expected behaviour as explained here: PHP while statement echoes duplicates
PHP
$sql = "
SELECT project.id, project.user_id AS owner_id, shared.user_id AS shared_id, project.content
FROM project
LEFT JOIN shared
ON project.id = shared.project_id
AND project.user_id <> ?
WHERE project.user_id = ?
OR shared.user_id = ?
";
$query = $mysqli->prepare($sql);
$query->bind_param("iii", $user_id, $user_id, $user_id);
$query->execute();
Alternate Table Structure
I suggest updating your table structure so that you have three tables (effectively: users, projects, and project_users). The project_user table then acts as a conduit between the two entities (users and projects). In this case storing the relationship between the two (i.e. owner vs shared with).
TABLE: user TABLE: project TABLE: project_user
id | email | | id | content | | id | user_id | project_id | role
---+-------------------- ---+------------------------------ ---+---------+------------+-----
1 | james#website.com | | 1 | Project for James | | 1 | 1 | 1 | 1
2 | hannah#website.com | | 2 | Some other project for James | | 2 | 1 | 2 | 1
3 | lucy#website.com | | 3 | Project for Hannah | | 3 | 2 | 3 | 1
| | | 4 | A new project for hannah | | 4 | 2 | 4 | 1
| | | 5 | Hannah's pride and Joy | | 5 | 2 | 5 | 1
| | | 6 | Lucy cracking down | | 6 | 3 | 6 | 1
| | | 7 | Lucy's second project | | 7 | 3 | 7 | 1
| | | 8 | Lucy's public stuff | | 8 | 3 | 8 | 1
| | | | | | 9 | 1 | 5 | 2
| | | | | | 10 | 3 | 5 | 2
| | | | | | 11 | 1 | 8 | 2
| | | | | | 12 | 2 | 8 | 2
SQL
Example: https://www.db-fiddle.com/f/imQZ6cvEEff4VgRQ4v22Qo/0
SELECT project.id, project_user.user_id, project_user.role, project.content
FROM project
JOIN project_user
ON project_user.project_id = project.id
WHERE project_user.user_id = ?;
PHP
$sql = "
SELECT project.id, project_user.user_id, project_user.role, project.content
FROM project
JOIN project_user
ON project_user.project_id = project.id
WHERE project_user.user_id = ?
";
$query = $mysqli->prepare($sql);
$query->bind_param("i", $user_id);
$query->execute();
You can use another relationship between members and projects with a table like this :
CREATE TABLE `project_members` (
`project_id` INT NOT NULL,
`member_id` INT NOT NULL,
`is_owner` TINYINT NOT NULL DEFAULT 0,
PRIMARY KEY (`project_id`, `member_id`));
This table allows you to have many members linked to many projects.
The column is_owner is a boolean to easily see if the member is the owner or if the project has been shared to him.
Also it would be good to add foreign keys to project_id and member_id.
school
+-----+-----------+----------+
| id | the_photo | column3 |
+-----+-----------+----------+
| 11 | NULL | abc |
| 22 | NULL | asf |
| 33 | NULL | asag |
+-----+-----------+----------+
school_images
+-----+-----------+-------+
| id | school_id | photo |
+-----+-----------+-------+
| 1 | 11 | 1 |
| 2 | 22 | 0 |
| 3 | 33 | 1 |
+-----+-----------+-------+
...
Need to insert values into the_photo column of school only if photo value = 1 for school_images like this:
School
+-----+-----------+
| id | the_photo |
+-----+-----------+
| 11 | 1 |
| 22 | NULL |
| 33 | 3 |
+-----+-----------+
Is there a simple query that can be written to do this for all rows? For one row i know how to insert it but how can i auto inert for multiple rows.
This might be what you're looking for: SELECT INTO.
Taken from the link:
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
BEWARE!! This answer is good only if you want to perform the above requested action upon a new insertion. Otherwise, you will need a different strategy
you should have something like this:
Select all you values from school_images then foreach them:
foreach($result as $res) {
if($res['photo'] == 1) {
// see step 2
} else {
// see step 3
}
}
if you have the value 1 in school_photos then:
INSERT INTO school (the_photo, colum3) VALUES ($res['id'], $some_value)
if you don't have it, then perform a normal insert like you did by now.
You can also use inner join to achieve that.
Update School inner join school_images on School.id = school_images.school_id and photo=1
set the_photo = school_images.id ;
You should use an INNER JOIN to join school with school_images:
UPDATE
school INNER JOIN school_images
ON school.id = school_images.school_id
AND school_images.photo=1
SET
school.the_photo=school_images.id
UPDATE school AS s, school_images AS si SET s.the_photo = si.id WHERE s.id = si.school_id AND si.photo = 1;
My data (simplified) looks like....
------------------------
| key | id | minspld |
------------------------
| 1 | 400 | 90 |
| 2 | 400 | 40 |
| 3 | 401 | 38 |
| 4 | 401 | 90 |
| 5 | 402 | 90 |
| 6 | 402 | 89 |
| 7 | 403 | 77 |
| 8 | 403 | 15 |
| 9 | 404 | 90 |
-----------------------
I am trying to do....
For each id, add all their minspld entries together
Display them in a table like above, but each id only showing once, and the minspld column showing the total per each id.
Here's what I'm using at the moment and I'm displaying all entries separately (eg, each person shows twice)
<table><thead><tr><th>ID</th><th>Mins Played</th></tr></thead>
<tbody>
<?php
$queryget = mysql_query("SELECT * FROM mlsstats ORDER BY id ASC") or die(mysql_error());
while ($row = mysql_fetch_assoc($queryget))
{
$id = $row['id'];
$minspld = $row['minspld'];
echo "<tr>";
echo "<td>".$id."</td>";
echo "<td>".$minspld."</td>";
echo "</tr>";
}
?>
</tbody></table>
How would I write this to make each id show only once in the HTML, but with the added totals of all their minspld entries? (eg, id 400 would have 130. id 401 would have 128. etc.)
If this isn't clear, please let me know.. and thanks for any help.
Please try changing your query to:
SELECT id, SUM(minspld) AS minspld FROM mlsstats GROUP BY id ORDER BY id ASC
You dont have to use a loop for this. You can simply do this with query
Just run the query and get two columns. id and its total
SELECT
m.id,
SUM(minspld) AS TCount
FROM mytable AS m
GROUP BY m.id
I have 4 tables that I need to pull data from. I need to count how many people are signed for a single event and see if a user is applied for an event.
These are my table setups:
TABLE: users
+----+----------+-------+--------+-------+
| id | username | level | class | guild |
+----+----------+-------+--------+-------+
| 1 | example1 | 100 | Hunter | blah |
| 2 | example2 | 105 | Mage | blah2 |
| 3 | example3 | 102 | Healer | blah |
+----+----------+-------+--------+-------+
ID is primary
TABLE: event_randoms
+----+----------+-------+--------+----------+----------+
| id | username | level | class | apped_by | event_id |
+----+----------+-------+--------+----------+----------+
| 1 | random1 | 153 | Hunter | 3 | 3 |
| 2 | random2 | 158 | Healer | 3 | 1 |
| 3 | random3 | 167 | Warrior| 1 | 3 |
+----+----------+-------+--------+----------+----------+
ID is primary
apped_by should be foreign key to users.id
event_id should be foreign key to events.id
TABLE: events
+----+------------+------------+-----------+-----------+-----------+
| id | event_name | event_date | initiator | min_level | max_level |
+----+------------+------------+-----------+-----------+-----------+
| 1 | event1 | date1 | 1 | 100 | 120 |
| 2 | event2 | date2 | 1 | 121 | 135 |
| 3 | event3 | date3 | 1 | 100 | 120 |
| 4 | event4 | date4 | 1 | 150 | 200 |
+----+------------+------------+-----------+-----------+-----------+
ID is primary
TABLE: event_apps
+----+----------+--------------+
| id | event_id | applicant_id |
+----+----------+--------------+
| 1 | 3 | 2 |
| 2 | 4 | 2 |
| 3 | 3 | 1 |
| 4 | 1 | 3 |
+----+----------+--------------+
ID is primary
event_id should be foreign key to events.id
applicant_id should be foreign key to users.id
I will be the first to admit that I am very new to this. I just learned how to use MySQL a few days ago. I can grab stuff from a single table, but I am unsure how to grab from multiple tables.
This is the SQL query I tried
SELECT DD_events.id, event_id, applicant_id, guild, level, class, DD_users.id
FROM DD_events, DD_event_apps, DD_users
WHERE DD_event_apps.event_id = DD_events.id
AND DD_event_apps.applicant_id = DD_users.id
and tried to print_r an array but the array turns up empty.
So a few questions pertain to this:
1: How would I count and display as a number how many people (users and randoms) are signed up for an event?
eg: event 3 should have 4 total (2 users and 2 randoms)
2: How do I see if a particular individual is signed for an event and display text based if they are or not?
eg: user 1 is signed up for event 3 so it would be "Registered" but user 2, who is not signed, would display "Not Registered"
3: I want to display info for who is signed for a particular event in 2 tables, 1 for users and another for randoms.
eg: Event 3 would have 2 users info (username, guild, class, level) under the users table and then 2 random users info (name, class, level, what user applied this person) in the random table.
Any and all help is appreciated even if you can answer 1 part.
I'm thinking this would be your base query:
SELECT
event.id,
app.applicant_id,
usr.guild,
usr.level,
usr.class,
usr.id AS Userid
FROM
DD_events event
JOIN
DD_event_apps app
ON (event.id = app.event_id)
LEFT JOIN
DD_users usr
ON (app.user_id = usr.id)
You can make modifications to this to aggregate it, like so:
SELECT
event.id,
COUNT(app.applicant_id) AS ApplicantCount,
COUNT(DISTINCT usr.guild) AS UniqueGuilds,
COUNT(DISTINCT usr.level) AS UniqueLevels,
COUNT(DISTINCT usr.class) AS UniqueClasses,
COUNT(DISTINCT usr.id) AS UniqueUsers
FROM
DD_events event
JOIN
DD_event_apps app
ON (event.id = app.event_id)
LEFT JOIN
DD_users usr
ON (app.user_id = usr.id)
GROUP BY
event.id
I could write those scripts for you, but I think this provides a good starting point for you to continue from. You'll find that T-SQL is fairly simple when you are trying to get the results you are looking for. Hope this helps!
<?php $query = "SELECT count(*) AS numbuh FROM DD_event_apps WHERE event_id = {$row['id']}";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
echo($query);
// Finally, we can retrieve all of the found rows into an array using fetchAll
$count = $stmt->fetchAll();
echo($count['numbuh']); ?>