SQL Join another table - php

I have a function that queries a table of student scores and return their total score, grade, registration number and score rank(position). I want to write an Sql join that will use the registration number returned from the scores table to get student names from the student table but the names are not returned and i am not getting any error.
public function get_subject_result(){
$subjectID = $this->input->get('subjectID');
$termID = $this->input->get('termID');
$sessionID = $this->input->get('sessionID');
//This Query which gave me headache actually ranks the total score and return positions
//$this->db->query("JOIN student ON main.stud_reg = student.reg");
$query = $this->db->query("SELECT (SELECT COUNT(*) + 1
FROM result ref
WHERE ref.total > main.total AND subject_id='".$subjectID."' AND term_id='".$termID."' AND session_id='".$sessionID."') as rank, ca1, ca2, exam,
total, remark, stud_reg, grade, subject_id
FROM result main JOIN student ON main.stud_reg = student.reg WHERE subject_id='".$subjectID."' AND term_id='".$termID."' AND session_id='".$sessionID."'
ORDER BY total DESC");
if ($query->num_rows() > 0) {
return $query->result();
}else{
return false;
}
}

Related

User defined variable not working in Mysql Code Igniter

I am trying to rank the rows based on when was it lasted updated partitioned by category name.
$query = "SELECT
category_name,
topic_title,
updated_ts,
#topic_rank := IF(#current_category = category_name, #topic_rank + 1, 1) AS topic_rank,
#current_category := category_name AS current_category
FROM topic_master
ORDER BY category_name, updated_ts DESC
";
$data = $this->db->query($query);
if($this->db->affected_rows() > 0)
{
return $data;
}
else
{
return false;
}
This query runs perfectly fine in MySQL and gives me the topic_rank as 1,2,3 and so on.
When I run this in CodeIgniter, I get topic_rank as 1 for all records.
What could be the issue ?
Try to use codeigniger database methods result_array():
$q = $this->db->query($query);
$data = $q->result_array();
Found an alternate way to solve this problem. No idea why the user defined variable was not working.
select category_name, topic_title as last_topic, updated_ts as last_activity, topic_pri_key as last_topic_id from
(
select
a.category_name, a.topic_title,
a.updated_ts,
a.topic_pri_key,
count(b.updated_ts)+1 as rank
from
topic_master a
left join
topic_master b
on a.updated_ts < b.updated_ts and a.category_name = b.category_name
group by 1,2,3,4
) a
where rank = 1

Getting relational table data

I have the following tables:
member
id, firstName, lastName
team
id, name
teamMember
id, teamId, memberId
I am trying to access the relational table so I can output the members firstName and Lastname:
$sql = "SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId
FROM teamMember
JOIN member
JOIN team
ON teamMember.memberId = member.id
WHERE dashboardId = 1 AND team.id = 1";
I have set a hard value in the team.id so I can test to make sure it returns the members of team 1 for now.
so the end goal here is that I need to access the relational table to give me back the names of members that are associated to the team id set in the select query by ID.
I am struggling to get the output need.
And return the values like so:
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "{$row['firstName']} {$row['lastName']}<br>";
}
}
The error I am seeing is:
Notice: Trying to get property of non-object in
Which refers to: if ($result->num_rows > 0) {
The output I want to see is the members firstName and lastName from the member table
You are probably want all the results or rows associated to the desired team id. But, Using a INNER JOIN you would only get a single row for one team because that is how JOIN works.
Instead you should use a query like this :
SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId
FROM teamMember
JOIN member
ON teamMember.memberId = member.id
WHERE dashboardId = 1 AND teamMember.teamId = 1"
Hope this would work.
However, As of bool(false), your query was also broken and would not get you desired results.
In your query you have joined three tables and defined the condition for only one. This would be what your query should look like
"SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId
FROM teamMember
JOIN member
ON teamMember.memberId = member.id
JOIN team
ON teamMember.teamId= team.id
WHERE dashboardId = 1 AND team.id = 1";

getting three records in descending order of each category using codeigniter

I've two categories and I want to fetch three records of each category later I found this link UNION query with codeigniter's active record pattern after this I change my DB_Active_rec file and add this code also
var $unions = array();
public function union_push($table = '') {
if ($table != '') {
$this->_track_aliases($table);
$this->from($table);
}
$sql = $this->_compile_select();
array_push($this->unions, $sql);
$this->_reset_select();
}
public function union_flush() {
$this->unions = array();
}
public function union() {
$sql = '(' . implode(') union (', $this->unions) . ')';
$result = $this->query($sql);
$this->union_flush();
return $result;
}
public function union_all() {
$sql = '(' . implode(') union all (', $this->unions) . ')';
$result = $this->query($sql);
$this->union_flush();
return $result;
}
and then I create codeigniter's function based query like this
$this->db->select("*");
$this->db->from("media m");
$this->db->join("category c", "m.category_id=c.id", "INNER");
$this->db->order_by("m.media_files", "DESC");
$this->db->limit(3);
$this->db->union_push();
$this->db->select("*");
$this->db->from("media m");
$this->db->join("category c", "m.category_id=c.id", "INNER");
$this->db->order_by("m.media_files", "DESC");
$this->db->limit(3);
$this->db->union_push();
$getMedia = $this->db->union_all();
create this
(SELECT * FROM media m INNER JOIN category c ON
m.category_id = c.id ORDER BY m.media_files DESC LIMIT 3)
UNION ALL
(SELECT * FROM media m INNER JOIN category c ON
m.category_id = c.id ORDER BY m.media_files DESC LIMIT 3)
Now it is fetching records but not properly I want to use only query, it showing six records first query fetch 3 records and second query fetch three records now records are duplicate I check the id of records it is 6,5,4 and again 6,5,4. It can be done also by PHP but I want to use query. Thanks in advance
I dont know code-igniter, but basicly you want it to do the union first and then apply the order by over the whole set. This would require a subquery. It should result in the following SQL query:
select * from
((SELECT * FROM media m INNER JOIN category c ON m.category_id = c.id )
UNION ALL
(SELECT * FROM media m INNER JOIN category c ON m.category_id = c.id)) T
ORDER BY m.media_files DESC LIMIT 3
Hope it helps you some.

Error while indexing data in another table and passing it to match another query

I have these tables: (unwanted columns were truncated in the question)
rooms:
room_id | room_type_id | room_number
room_types:
room_type_id | room_type | room_type_default_price
reservations:
reservation_id room_type | checkin | checkout
When user searches for available rooms by entering desired room type, arrival date, departure date it, the available room types must be populated in a dropdown. However there are two problems, one is known and one is unknown. Below code returns nothing but an "array to string conversion error" on page (View) load.
The known problem is that, the dropdown for the room type is filled with data from room_types table as well. For JS/jQuery calculation I have concatenated room_type column and room_type_default_price column on populating. So the generated HTML is like this:
Double Room
Therefore the user input $room_type comes in as, for example "Double Room_20000" where originally no column data exists that way. In room types table, room_type column has "Double Room" though. How do I separate these two values and get room_type_id to $room_type_id ?
Model:
function searchRoomType($room_type) {
$query = $this->db->query(" SELECT room_type_id FROM room_types WHERE room_type = '$room_type' LIMIT 1");
return $query->result();
//return $room_type_id;
//print_r ($room_type_id);
}
function searchRooms($room_type, $start_date, $end_date, $tmpRoomNumber = array()) {
$room_type_id = $this->searchRoomType($room_type);
$query = $this->db->query(
"SELECT a.room_number
FROM rooms a LEFT OUTER JOIN ( SELECT room_number
FROM reservations
WHERE checkin >= '$start_date'
AND checkout <= '$end_date'
) b
ON a.room_number = b.room_number
WHERE a.room_type_id = '$room_type_id'
AND a.housekeeping_status = 'Clean'
AND b.room_number is NULL
GROUP BY a.room_type_id
ORDER BY a.room_number ASC");
if($query->num_rows()>0) {
foreach($query->result_array() as $row) {
$tmpRoomNumber[$row['room_number']] = $row['room_number'];
}
}
return $tmpRoomNumber;
}
i think you should change the function searchRoomType like this
function searchRoomType($room_type) {
$query = $this->db->query(" SELECT room_type_id FROM room_types WHERE room_type = '$room_type' LIMIT 1");
foreach ($query->result() as $row)
{
$room_type_i=$row->room_type_id;
}
return $room_type_id;
}

mysql return the total of rows for each user_id

$sql = "SELECT * FROM books LEFT JOIN users
ON books.readby=users.user_id WHERE users.email IS NOT NULL";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row['readby']. " - read 10 books";
} //while ends
this is the code I have so far. I am trying to retrieve the number of books read by each user
and echo the results. echo the user_id and number of books he/she read
books table is like this : id - name - pages - readby
the row readby contains the user id.any ideas/suggestions? I was thinking about using count() but Im not sure how to go about doing that.
A subquery can return the count of books read per user. That is left-joined back against the main table to retrieve the other columns about each user.
Edit The GROUP BY had been omitted...
SELECT
users.*,
usersread.numread
FROM
users
/* join all user details against count of books read */
LEFT JOIN (
/* Retrieve user_id (via readby) and count from the books table */
SELECT
readby,
COUNT(*) AS numread
FROM books
GROUP BY readby
) usersread ON users.user_id = usersread.readby
In your PHP then, you can retrieve $row['numread'] after fetching the result.
// Assuming you already executed the query above and checked errors...
while($row = mysql_fetch_array($result))
{
// don't know the contents of your users table, but assuming there's a
// users.name column I used 'name' here...
echo "{$row['name']} read {$row['numread']} books.";
}
You can use count() this way:
<?php
$count = mysql_fetch_array(mysql_query("SELECT COUNT(`user_id`) FROM books LEFT JOIN users ON books.readby=users.user_id WHERE users.email IS NOT NULL GROUP BY `user_id`"));
$count = $count[0];
?>
Hope this helps! :)

Categories