SQL select query to find count from given table - php

I have one table in database -> applicants_detail which has two column
applied_personid and applied_courseid.
College provides number of courses.
I have the given id to applied_courseid, that is written like this:
arts--1
science--2
maths--3...
And applied_personid which contains applied person id.
I need to count how many people applied for the course, like in the page it should show:
maths------15 people_applied
science------20 people_applied
I tried this query:
$query="select * from people where people_id in(select applied_personid from applicants where applied_courseid =".$_GET['postcourseid']." )";
And the code to find count is not able to show count in the table.
<?php
$count=0;
while($row=mysql_fetch_array($res))
{
echo '<tr> <td width="10%">'.$count.'
<td width="50%">'.$row['student_fnm'].'
<td width="50%">'.$row['applied_courseid'].'
<td width="30%">course name
';
$count++;
}
?>

You just need to group by applied_courseid. This should do it.
select applied_courseid, count(applied_personid) as `count`
from
applicants_detail
group by applied_courseid
Then if needed use the results here to join to the other tables
which you probably have (that would give the you course name e.g.).

Try this to get all data:
SELECT course_name, applied_courseid as course_id, count(applied_personid) as `student_number`
FROM applicants_detail
INNER JOIN course_detail ON course_detail.course_id = applicants_detail.course_id
GROUP BY applied_courseid

Related

For each SQL result, another SQL query? in PHP

I need help at getting data from MySQL Database. Right now I have a query that gives me:
Tournament ID
Tournament Name
Tournament Entry fee
Tournament Start and End date
For tournaments I am registered in. Now I want, for each tournament I am registered in, to count how many users are in that tournament, my points in that tournament, etc.
That info is in table called 'ladder'
ladder.id
ladder.points
ladder.userFK
ladder.tournamentFK
Database: http://prntscr.com/99fju1
PHP CODE for displaying tournaments I am registered in:
<?php
include('config.php');
$sql = "SELECT distinct tournaments.idtournament, tournaments.name, tournaments.entryfee, tournaments.start, tournaments.end
from tournaments join ladder
on tournaments.idtournament= ladder.tournamentFK and ladder.userFK=".$_SESSION['userid']."
group by tournaments.idtournament";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
$tournament="<li class='registered' data-id=".$row['idtournament']." data-entryfee=".$row['entryfee']." data-prize=".$tournamentPrize."><span class='name'>".$row['name']."</span><span class='entry-fee'>Entry fee: ".$row['entryfee']."€</span><span class='prize-pool'>Prize pool: €</span><span class='date-end'>".$row['start']."-".$row['end']."</span><span class='btns'><button>Standings</button></span></li>";
echo $tournament;
}
}
$conn->close();
?>
Usually you can combine JOIN, COUNT() and GROUP BY in your query.
Some examples:
MySQL joins and COUNT(*) from another table
This would be the query I think.Change column and table name if its not correct. Not tested but I am sure this will give you some idea to make required query
select count(ladder.tournamentId)as userCount,tournaments.name
from
ladder left join tournaments
on ladder.tournamentId = tournaments.id
where ladder.tournamentId in
(
select tournaments.id from
tournaments left join ladder
on ladder.tournamentId = tournaments.id
where ladder.userId='yourId'
) and ladder.userId <> 'yourId'
group by ladder.tournamentId

group a query's values together based on its id

I have data coming from the database , i am using JOIN(s) to select data from different tables,I need to be able to group the data together based on the specific id of the user in relation to the specific course, as an email needs to be sent based on the selection and within this selection(using a radio button) it will allow admin to be able to email all the users assigned to that specific category selected
i am currently getting duplicated data, like the users details will show on each category instead of being in one single category to pass into the array to email. I only need to select one radio button per category/course but now i am getting multiple radio buttons.
here is my query:
$query="SELECT * FROM course_student
JOIN course ON course.course_id=course_student.course_id
JOIN student ON student.student_id=course_student.student_id
WHERE course.course_id=course_student.course_id
ORDER BY course.course_id";
this is my loop to select data -- it's creating duplicate names for the entries where i just want one name with all of the data that is supposed to be in it
$result=mysqli_query($connection,$query);
confirmation($connection);
while($course_email_students = mysqli_fetch_assoc($result)){
$course_email = $course_email_students['student_email'];
$course_name = $course_email_students['course_name'] ."<br/>";
here is my html:
<input type="radio" name="course_mail[]" value="<?php echo $course_email ;?>">
<?php echo $course_name ?>
<?php } ?>
here is more code
html
<form action ="#" method="POST">
<P> <label for="">Send to specific student courses</label>
</p>
<?php // email specific students
$query = "SELECT student.student_email, course.course_name, course.course_id
FROM course_student
JOIN student ON student.student_id=course_student.student_id
JOIN course ON course.course_id=course_student.course_id
GROUP BY student.student_email, course.course_id
ORDER BY course.course_id";
$result=mysqli_query($connection,$query);
confirm_query($connection);
while($course_email_students=mysqli_fetch_assoc($result)){
$course_student_email=$course_email_students['student_email'];
$course_student_email_name=$course_email_students['course_name'] ."<br/>";
var_dump($course_email_students['student_email']);
?>
<input type="radio" name="course_email[]" value="<?php echo $course_student_email ;?>">
<?php echo $course_student_email_name ?>
<P> <label for="">Message</label>
<p><textarea rows="10" cols="20" name="message"></textarea></p>
</p>
<input type="submit" name="submit" value="send">
here is the php for testing to see what comes through
if(isset($_POST['submit'])){
// do validation
if(isset($_POST['course_email'])){
var_dump($_POST['course_email']);
}
}
From the PHP you've posted, it appears that you are just using data from two, possibly three columns in your query. If so, it is much more efficient to select the specific columns you're interested in in the SQL. There's also a redundancy in the query where you're using the same condition for a WHERE as you have in a JOIN:
$query="SELECT student.student_email, course.course_name, course.course_id FROM course_student
JOIN student ON student.student_id=course_student.student_id
JOIN course ON course.course_id=course_student.course_id <-- !!!
WHERE course.course_id=course_student.course_id <-- !!!
ORDER BY course.course_id";
There are two ways of selecting unique combinations of results with this select query; you can use DISTINCT or GROUP BY.
DISTINCT:
$query = "SELECT DISTINCT student.student_email, course.course_name, course.course_id
FROM course_student
JOIN student ON student.student_id=course_student.student_id
JOIN course ON course.course_id=course_student.course_id
ORDER BY course.course_name";
GROUP BY:
$query = "SELECT student.student_email, course.course_name, course.course_id, student.student_id
FROM course_student
JOIN student ON student.student_id=course_student.student_id
JOIN course ON course.course_id=course_student.course_id
GROUP BY student.student_email, course.course_name
ORDER BY course.course_name";
Now for the PHP code:
$c_name = ''; # course name
$c_id = ''; # course ID
$students = array();
while($aa = mysqli_fetch_assoc($result){
if ($aa['course_name'] !== $c_name) {
# the course name has changed. print out the course and student data
make_radios($c_name, $c_id, $students);
# set c_name to the new course name
$c_name = $aa['course.course_name'];
$c_id = $aa['course.course_id'];
# set the students to the new student
$students = array( $aa['student.student_email'] );
}
else {
# add this student to the list of students
$students[] = $aa['student.student_email'];
}
}
# print out the last set of data
make_radios( $c_name, $c_id, $students );
function make_radios( $course_name, $course_id, $email_arr ) {
$html = '<input type="radio" id="email'
. $course_id . '" name="course_email[]" value="'
. implode(',', $email_arr) . '"> <label for="email'
. $course_id . '">$course_name</label>';
# I don't know if you want to list all the email addresses or not... in case you do:
$html .= "<ul>";
foreach ($email_arr as $e) {
$html .= "<li>$e</li>\n";
}
$html .= "</ul>";
# append the message box
$html .= '<label for="message' . $course_id . '">Message</label>'
. '<textarea id="message' . $course_id . '" rows="10" cols="20" name="message">'
. "</textarea>\n";
echo $html; # or you could return $html
}
I would not recommend that you have the email addresses on the form--I'd use the student IDs and the students' names instead, and then have your script pull the appropriate email addresses from the database--but it's up to you, obviously.
Please read through the code and check you understand what it's doing. I'm happy to answer any questions.
Group and Order are words that have meaning both in English and in SQL jargon. You've said you want your values grouped. I think you mean, in SQL terms, you want them ordered, in such a way that each course's student emails are together.
There are some problems with your query.
First, Pro tip: Avoid using SELECT * in software. (It's OK when you're troubleshooting databases, but it's wasteful and confusing in software, especially when you're JOINing more than one table.)
Second, you have this condition repeated in both your JOIN...ON and your WHERE clause. That's redundant.
course.course_id = course_student.course_id
Leave it in your ON clause and out of your WHERE clause.
Third, your result set's order is underdetermined. This may not matter, but you are ordering only by course id. If you care whether your result set is ordered by student email, then mention it in the ORDER BY clause.
Fourth, you do have three tables. But one of them, course_student, appears to be a classic join table allowing there to be a many-to-many relationship between courses and students. So it seems likely you only have two tables with actual application data items in them.
Finally, from the code in your question it looks like you want
course_id
course_name
student_email
in your result set generated by your SELECT query. Your question's narrative mentions category, but because you've used SELECT * we can't tell what you mean by that.
To get the unique values of those three fields in your result set, use this query:
SELECT DISTINCT
course.course_id,
course.course_name,
student.student_email
FROM course_student
JOIN course ON course.course_id=course_student.course_id
JOIN student ON student.student_id=course_student.student_id
ORDER BY course.course_id, student.student_email
The DISTINCT qualifier eliminates duplicates.
From your comment, it's still hard to tell what you want. But it seems that you want to try this:
SELECT GROUP_CONCAT(DISTINCT course.course_name),
student.student_email
FROM course_student
JOIN course ON course.course_id=course_student.course_id
JOIN student ON student.student_id=course_student.student_id
GROUP BY student.student_email
ORDER BY student.student_email
Or maybe you want this.
SELECT GROUP_CONCAT(DISTINCT student.student_email),
course.course_name
FROM course_student
JOIN course ON course.course_id=course_student.course_id
JOIN student ON student.student_id=course_student.student_id
GROUP BY course.course_name
ORDER BY course.course_name
This second one is going to fail in your large courses because of a limitation of GROUP_CONCAT(). You may need to write application code to organize your web page course by course, or student by student.

how to select data from 2 table of databace in mysql....?

I have 2 table of date , student_info and student_payment in my databace...
in student_info i have:
id, student_id,student_mail,student_pass,student_name,...
and in student_payment have:
id,student_id,student_payment_id,student_payment_date,...
so my problem is here, i wanna select student_name where student_id form student_info but i have problem and mysql give my an error:
$db->connect();
$sql = "SELECT * FROM `student_payment`";
$rows = $db->fetch_all_array($sql);
$student_id = $rows['student_id'];
$sql2 = "SELECT * FROM `student_info` WHERE student_id=$student_id";
$rows2 = $db->fetch_all_array($sql2);
$db->close();
foreach($rows as $record ){
// i wanna to use student_name in first line
echo "\n<tr>
<td>$record[student_id]</td>
<td dir=\"ltr\">$record[student_payment]</td>
<td dir=\"ltr\">$record[student_payment_id]</td>
<td dir=\"ltr\">$record[student_payment_bank]</td>
<td dir=\"ltr\">$record[student_payment_type]</td>
<td dir=\"ltr\">$record[student_payment_date]</td>
<td dir=\"ltr\"></td>
</tr>\n";
}
but i dont know how to connect student_id and student_name and use in foreach because i have 2 rows of data.
(i'm a beginner in PHP / MySql)
Instead of querying database twice, you can instead join the tables to get the rows you want. Try to execute the query below in PhpMyAdmin or directly on MySQL Browser.
SELECT a.*, b.*
FROM student_info a
INNER JOIN student_payment b
ON a.student_ID = b.student_ID
-- WHERE ...if you have extra conditions...
ORDER BY b.student_payment_date DESC
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
It is possible to fix it with INNER JOIN, you can join 2 tables and use both values from 1 query.
http://www.w3schools.com/sql/sql_join_inner.asp
Or you can use the OOP way, not sure if that is what you need.
Make 2 objects from the 2 query's and put them in a foreach.
try this
$sql2 = " SELECT * FROM `student_info` WHERE student_id= '$student_id' ";
try this
$sql2 = "SELECT * FROM `student_info` WHERE student_id IN ($student_id)";
foreach($rows as $record ){
// i wanna to use student_name in first line
echo "\n<tr>
<td>$record[student_id]</td>
<td dir=\"ltr\">".$record['student_payment']."</td>
<td dir=\"ltr\">".$record['student_payment_id']."</td>
<td dir=\"ltr\">".$record['student_payment_bank']."</td>
<td dir=\"ltr\">".$record['student_payment_type']."</td>
<td dir=\"ltr\">".$record['student_payment_date']."</td>
<td dir=\"ltr\"></td>
</tr>\n";
}
Use Mahmoud Gamal code
But always select the needed columns only not all because
In future number of columns in table may increase which may decrease the performance of your application.
Also it may contain some important information not to be leaked.
It seems like you want a report of all payments made. The student name is to be displayed with the payment information. The results will probably have more than one payment per student.
This result is ordered by student name, and then payment date (most recent first)
SELECT s.student_name, sp.*
FROM student_payment sp
INNER JOIN student_info s ON s.student_ID=sp.student_ID
ORDER BY s.student_name ASC, sp.student_payment_date DESC
try to join the table and use single query instead of two -
$sql = "SELECT * FROM student_info, student_payment
WHERE student_info.student_id=student_payment.student_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! :)

Select from one table, and count from another table in same query

I have quite a bit of knowledge about SQL queries.
I'm trying to make gallery, and I need to select categories from table "cat_photos", which contain rows (id,name,cover,photo) and count number of photos from table "photos" which contain rows (id,thumb,photo,category).
Here is code which i use:
1) Selecting categories
$query = mysql_query("SELECT * FROM cat_photos ORDER BY ID DESC");
while($data = mysql_fetch_array($query)) {
echo "<li><a href='photos.php?cat=$data[id]'><img src='galleries/categories/$row[image]' alt='$row[name]' /></a>
<div class='photodesc'><div class='catname'><a href='photos.php?cat=$row[id]'>$row[name]</a></div>
<div class='catcount'>Number of photos in category</div></div></li>"; }
2) Counting number of photos in category
$query = mysql_query("SELECT category, COUNT(photo) FROM photos GROUP BY category") or die(mysql_error());
while($row = mysql_fetch_array($query)){
echo "Number of photos is ". $row['COUNT(photo)'] ." in cateogry ". $row['category'] .".";
echo "<br />"; }
Separated all works, but I can't find a way to merge them into one query.
I have googleing for "UNION", "JOIN", "LEFT JOIN" options in MySql query but I could't together the pieces.
I wonder if this is in general possible?
How in order that query look like?
Try this, it should work :
SELECT cat_photos.*, count(photos.id) as number_photos
FROM cat_photos
LEFT JOIN photos ON photos.category = cat_photos.id
GROUP BY cat_photos.id, cat_photos.name, cat_photos.image
ORDER BY cat_photos.id
The number of photos will be accessible trough $row['number_photos'].
Just use your second query and join the wanted category elements.
Something quick and dirty would be:
SELECT c.category, COALESCE(COUNT(p.photo),0) as photos FROM photos p, cat_photos c
WHERE c.category = p.category
GROUP BY category
Since I don't know your exact database setup just change the selected elements to the ones you really need.
//edit: Put in Coalesce to get categories with 0 photos.
Don't SELECT *. Instead select individual columns and then join:
SELECT
cat_photos_main.id, cat_photos_main.category, cat_photos_main.photodesc, cat_photos_counts.num_photos
FROM cat_photos cat_photos_main
LEFT OUTER JOIN (SELECT category, count(*) AS num_photos FROM photos GROUP BY category) cat_photos_counts
ON cat_photos_main.category = cat_photos_counts.category

Categories