I have two tables- One with attendance details and another one with student detail. The following are the table structures:
tbl_attendance
aid date attendance
1 2017-03-09 5,6,9
2 2017-04-06 12,6,10
tbl_students
student_id name
5 John
6 Bryan
9 Anna
10 Mathew
12 Susan
Now, I want to display the names of the absentees in the view as something like say. for example:
Date Absentees
2017-03-09 John, Bryan, Anna
2017-03-06 Susan, Bryan, Mathew
I was trying to do it with FIND_IN_SET()..but it seems bad luck..Is there a better way to sort this out?
UPDATE
I used this query instead and it echoed only the first id's name in each row...
$query = $this->db
->select("tbl_attendance.*,tbl_students.name")
->from("tbl_attendance")
->join("tbl_students","tbl_students.student_id=tbl_attendance.attendance")
->where('FIND_IN_SET(tbl_students.student_id, tbl_attendance.attendance)')
->GROUP_BY('tbl_students.student_id')
->get()->result_array();
But as there are three numbers separated by commas in each row I want the rest to be echoed as well.
This Works
$query = $this->db
->select("td.Date, GROUP_CONCAT(ts.student_name SEPARATOR ',')")
->from("tbl_students AS ts")
->join("tbl_attendance AS ta","find_in_set(ts.st_id,ta.attendance)<> 0","left",false)
->get();
How about that ?
$query = $this->db
->select("td.Date, GROUP_CONCAT(ts.student_name)")
->from("tbl_students AS ts")
->join("tbl_attendance AS ta","find_in_set(ts.st_id,ta.attendance)","left",false)
->get();
You can try query like this,
SELECT a.`date`,group_concat(s.student_name)
FROM tbl_attendance a,tbl_students s
WHERE FIND_IN_SET(s.st_id, a.attendance) group by `date`;
Description :
FIND_IN_SET that allows you to find the position of a string within a comma-separated list of strings.
Syntax:
FIND_IN_SET(needle,haystack);
Hope this will solve your problem.
Here comma separated category IDs are saved in row 'category' eg., '12,15,7,19'
$category_ID = 15;
$this->db->select('*');
$this->db->from('products');
$this->db->where('FIND_IN_SET("'.$category_ID.'","category") <>','0');
$this->db->where('deleted','0');
$this->db->order_by('product_ID', 'DESC');
I hope this helps CI developers to use FIND_IN_SET.
Related
i want to count the different rows in CodeIgniter...
I have a table like this
NAME | ZIPCODE
Mike | 12345
Marc | 51233
TEST | 12345
Now i want a Result of "2" cause there 2 different Zipcodes.
I tried so much, but dont get this :(
$this->db->select('zipcode, count(*)');
$getAll = $this->db->get('ads');
echo $getAll->num_rows();
but dont get result of or anything... idk how i can make this.
Please help
//EDIT:
Okay i found it. Sorry for Question. Here is the Answer
$this->db->distinct();
$this->db->select('zipcode');
$getAll = $this->db->get('ads');
echo $getAll->num_rows();
you can use this:
$query = $this->db->query('select count(1) as x from your_table_name group by zipcode');
$row= $query->row();
$x = $row->x;
You could use group_by() in your query as follows.
$this->db->select('zipcode', 'count(*) as totalcount');
$this->db->group_by('zipcode');
$this->db->get('ads');
$this->db->select('*')->from('myTable')->where('name',$user_name)->get()->results_array();
If i do this after the query above,
echo $this->db->count_all_results();
Even though myTable has rows :
Table: myTable Column1 name: id Column2 name: name
row1 - 1 row1 - peter row2 - 2 row2 - peter
It would echo 1, although there are 2 peters. My thoughts is that i returned the results as an array.
How should i return the results? Active_records class does not show how to. It only shows another format where i type in the query myself manually. I don't like doing queries like that.
Although might i ask for professionals' opinion. Which is better. The way im doing it or the examples in active records like,
$query = $this->db->get('mytable');
Although they dont show an example where you specifically select column names.
You should do it in 2 steps.
$query = $this->db->select('*')->from('myTable')->where('name',$user_name)->get();
$result = $query->result_array();
$countResult = $query->num_rows();
I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}
I'm trying to wrap my head around this, but I seem to go in circles. I'm trying to list a users topics one by one, with the quotes belonging to that specific topic underneath. If that makes sense.
I have 3 tables, like so:
[USERS] user_id username
[TOPICS] topic_id user_id topic_name
[QUOTES] quote_id topic_id quote_name
I want to be able to do something like this in my view:
Username: Thomas
Topic 1: Whatever
Quotes: One quote, another quote, and a third quote, all belonging to Topic 1.
Topic 2: Another topic from Thomas
Quotes: Yes indeed, Okay thanks, I love Stack Overflow, These quotes belong to Topic 2.
But I can't get it to work, I've been trying everything, including weird stuff like:
public function get_quotes()
{
$this->db->select('*');
$this->db->from('topics');
$this->db->join('quotes', 'topic_id = quote_id');
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach ($query->result() as $row) {
$data[] = $row;
}
}
return $data;
}
Is this strange, should I instead try using 'where' instead? Something like:
$this->db->where('user', $user_id);
$this->db->where('topic', $topic_id);
$this->db->where('quote', $quote_id);
I really appreciate any help I can get, or just a finger pointed in the right direction!
Right off the bat I would ask "What is not working?", secondly I would suggest you run the profiler to show you the EXACT SQL being generated, so that you can make a valid assessment of where the ACTIVE QUERY is failing you.
To use the profiler, stick this into your controller:
$this->output->enable_profiler(TRUE);
It will result in a nice output of all DB calls, all POST vars, etc;
Reference here: http://codeigniter.com/user_guide/libraries/output.html
UPDATE
So to fully do what you want, you need a query that returns the following columns:
user_id, username, topic_id, topic_name, quote_id, quote_name
Here is the active query you want (you can also use method chaining if that is clear enough):
$this->db->select('u.user_id, u.username, t.topic_id, t.topic_name, q.quote_id, q.quote_name');
$this->db->from('users u');
$this->db->join('topics t', 't.user_id = u.user_id'); // this joins the user table to topics
$this->db->join('quotes q', 'q.topic_id = t.topic_id'); // this joins the quote table to the topics table
$query = $this->db->get();
Your result set will then be something like:
user_id | username | topic_id | topic_name | quote_id | quote_name
1 |Thomas |1 |Whatever |1 |One quote, anot...
2 |Ryan |4 |Another... |6 |To be or not to...
Once you have that result set, simply loop through the data to output it, and check to see if you have multiple quotes from the same person (say sort by user_id and do a test on the 2nd loop if its the same person, otherwise output the new users name).
If you want all of the quotes for a specific user:
$this->db->join('TOPICS t', 'u.user_id on t.user_id')
->join('QUOTES q', 't.topic_id on q.topic_id')
->where('u.user_id', $userId)
->get('USERS u');
// I always echo my queries when developing to make sure they are what i'm expecting
echo $this->db->last_query();
If you want all of the quotes for all of the users
$this->db->join('TOPICS t', 'u.user_id on t.user_id')
->join('QUOTES q', 't.topic_id on q.topic_id')
->get('USERS u');
echo $this->db->last_query();
I have a Relationship table that links teachers to students
Teacher Student
1 1
1 2
2 1
2 3
The Students table then has specific data about the students
Id Date of birth First Name
1 1990-10-10 Bill Smith
2 1989-01-03 Adam Smithson
I want to select all the students who are students of teacher 1. Right now i do this way (this is propel ORM syntax).
$relationships = RelationshipQuery::create()->filterByTeacher($teacherid)->find();
foreach($relationships as $relationship){
$studentId = $relationship->getStudent();
//use the studentId to get the actual student object
$student = StudentQuery::create()->findPk($studentId);
//after I get the student, I add it to an array
$students[] = $student;
}
The problem with this is that I end up with an array, and not the usual propelCollection that we end up with when we do a normal ->find(). Is there a way to clean up this query a bit (use joins or something like that) so that I end up with a PropelCollection from the start?
You should define your schema for the relationship like this: http://www.propelorm.org/wiki/Documentation/1.5/Relationships#Many-to-ManyRelationships
The code you're asking for is very easy:
$teacher = TeacherQuery::create()->findOneById($teacherId);
$students = $teacher->getStudents(); //Your students collection