How to count amount of students per university - php

I have a SQL database of university students, with the following details:
Table_name: register
Column_names: position, tertinst
The data in the database will look something like this:
Coach..........UCT
Athlete........Tukkies
Official.......University of JHB
Athlete........Tukkies
Athlete........Tshwane Tech
Manager........UCT
I need to count the amount of students who are athletes(position), per university(tertinst) and the output has to be something like this:
UCT.....................735
University of Jhb.......668
Tukkies.................886
this is my attempt:
$positionx = 'Athletes';
include_once 'core/includes/db_connect.php';
$sql = "SELECT tertinst, COUNT(position) FROM register WHERE position = '$positionx' GROUP BY tertinst ";
$result = $conn->query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['COUNT(tertinst)'] . '......' . $row['COUNT(position)'];
}
$conn->close();
I get no result when the code is executed and I have searched for a different solution for hours, without success.

I made a few mistakes, and corrected the syntax in the sql count, as well as the echo. Here is the solution to my problem:
<?php
include_once 'core/includes/db_connect.php';
$sql = "SELECT tertinst, COUNT(*) total FROM register WHERE position = 'Athletes' GROUP BY tertinst ";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$tertinst = $row["tertinst"];
echo $tertinst . '......' . $row['total'] . '<br>';
}
$conn->close();

Related

How to count the sum of the value in 1 column and with the same value of another column?

I'm going to count the sum of the value in rmNum column and with the same value of rmType.
From the table as shown in image above, can someone please teach how to to sum up the value of rmNum by referring to the same "keyword" of rmType?
i am new to PHP and i still get confusing about this even i went through the teaching part in other websites and questions that asked in Stackoverflow.
Edit 2:
<?php
require_once 'dbconnect.php';
$sql = "SELECT * FROM room";
$result = mysqli_query($conn, $sql);
echo $conn->error;
while($row = mysqli_fetch_array($result)) {
$typeRow = $row;
}
$sql1 = "SELECT rmType, SUM(rmNum) as total FROM room GROUP BY rmType";
$result = mysqli_query($conn,$sql1);
while ($row1 = mysqli_fetch_assoc($result)) {
echo $row1['rmType'] . ' had ' . $row1['total'] . ' room reservations';
}
mysqli_close($conn);
?>
this is the coding i used after all, it still give me Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean
You can use a GROUP BY statement:
$sql = "SELECT rmType, SUM(rmNum) as total FROM table GROUP BY rmType";
where table is the name of the table. This will return a table with two columns: the rmType and the total sum of rmNum for that type.
You can then process it like:
$sql = "SELECT rmType, SUM(rmNum) as total FROM table GROUP BY rmType";
$result = $mysqli->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row['rmType'] . ' had ' . $row['total'] . ' room reservations';
}
EDIT: In case you want the total sum, you do not need to group, you can simply use:
$sql = "SELECT SUM(rmNum) as total FROM table";
$result = $mysqli->query($sql);
if ($row = $result->fetch_assoc()) {
echo 'The total number of reservation rooms is ' . $row['total'];
}

Problems getting my info from table join to display in PHP

{Connecting 2 tables together (with teacher ID and teacher name)
I have created the join and I have tested in SQL. Seems good. I am trying to print it on the screen.
$classandteacher = "SELECT person_name FROM people RIGHT OUTER JOIN classes ON classes.instructor_id=people.instructor_id ASC";
$result = mysqli_query($dbc, $classandteacher){
while($row = mysqli_query($dbc, $result));
$teacher = $row["person_name"];
echo ("Teacher: " . $teacher . "<br>");}
It's because the While Loop isn't correctly formatted.
Remove the ; and put it into {}
You also need to use mysqli_fetch_assoc($result) to get the Array from the query
$classandteacher = "SELECT person_name FROM people RIGHT OUTER JOIN classes ON classes.instructor_id=people.instructor_id ASC";
$result = mysqli_query($dbc, $classandteacher);
if(!$result) { //If your MYSQL query is throwing an error
error_log(mysqli_error());
}
while($row = mysqli_fetch_assoc($result))
{
$teacher = $row["person_name"];
echo "Teacher: " . $teacher . "<br>";
}
Or try using
mysqli_fetch_array instead
$classandteacher =
"SELECT
person_name FROM
people RIGHT OUTER JOIN classes ON
classes.instructor_id
=
peopleinstructor_id ASC";
$result =
mysqli_query($dbc,$ classandteacher);
if(!$result) { //If
your MYSQL query is
throwing an error
error_log(mysqli_er
ror() );}
while($row =
mysqli_fetch_array(
$result))
{
$teacher = $row
["person_name"];
echo "Teacher: " . $
teacher . "<br>"; }

What is an SQL query for counting records that are existing more than once in a database?

<?php
mysql_connect("localhost", "root", "");
mysql_select_db("students");
$id = $_POST['id'];
$grade = $_POST['grade'];
$query = "INSERT INTO `st_table` (`St_id`,`Grade`) VALUES ('$id','$grade')";
$result = mysql_query($query);
$query = "SELECT * from `st_table`";
$result = mysql_query($query);
echo "<table>";
echo "<th>St_id</th><th>Grade</th>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['St_id'] . "</td><td>" . $row['Grade'] . "</td></tr>";
}
This code adds values into a table both ID and Grade. I want another query that will be able to count how many As, Bs, Cs, etc. and OUTPUT it on an html table.
Here, Your query is ok just group by Grade not Grades
"SELECT `Grade`, COUNT(*) AS count FROM `st_table` GROUP BY `Grade`";
Here is sqlfiddle
After edit
The query i am mentioning should work for you, you can check fiddle for that as for as you modified code is concerned you have to change your table a bit since you are going to include St_id as well so make it 3 column and correspondingly change query too.

mysqli result amounts depending on fetch inside while

I am fetching rows from a mysql table (jobs). Inside of that fetch, I am also fetching from another table (accounts) [to receive account api keys all depending on what ID_ASSOC is attacted to the job]: below is the code
$sql = "SELECT * FROM jobs";
$query = mysqli_query($db_conx, $sql);
while($row = mysqli_fetch_assoc($query)){
echo $row['action'];
echo "<br/>";
$job_poster_id = $row['id_assoc'];
$sql = "SELECT * FROM accounts WHERE id_assoc='$job_poster_id'";
$query = mysqli_query($db_conx, $sql);
while($rows = mysqli_fetch_assoc($query)){
$username = $rows['twitter_username'];
$consumer_key = $rows['consumer_key'];
$consumer_secret = $rows['consumer_secret'];
$access_token = $rows['access_token'];
$access_token_secret = $rows['access_token_secret'];
}
echo $job_poster_id ;
echo "<br/>";
echo $twitter_username;
echo "<br/>";
echo "----------------------------------";
echo "<br/>";
}
OUTPUT:
specific-message
4
admin
----------------------------------
When I do this, I only get one row output..and I can't seem to find out why. I want the above out put to repeat as many times as it has rows, and it's only doing one row (with the account fetch in the code). However when I do it without the internal fetch (accounts fetch), it returns multiple rows just as desired. Why is this? (below is sample code WITHOUT the accounts fetch):
$sql = "SELECT * FROM jobs";
$query = mysqli_query($db_conx, $sql);
while($row = mysqli_fetch_assoc($query)){
echo $row['action'];
echo "<br/>";
$job_poster_id = $row['id_assoc'];
echo $job_poster_id ;
echo "<br/>";
echo "----------------------------------";
echo "<br/>";
}
OUTPUT:
specific-message
4
----------------------------------
specific-message
1
----------------------------------
specific-message
2
----------------------------------
$query = mysqli_query($db_conx, $sql);
while($row = mysqli_fetch_assoc($query)){
echo $row['action'];
echo "<br/>";
$job_poster_id = $row['id_assoc'];
$sql = "SELECT * FROM accounts WHERE id_assoc='$job_poster_id'";
$query = mysqli_query($db_conx, $sql);
The problem is that you're using $query for the inner and the outer query.
When the inner query runs, and it steps through the loop, it's iterating to the end of the result set; when the outer while loop runs, mysqli_fetch_assoc($query) is returning false, because you're already at the end of the result set - just not the result set you were expecting.
You can fix this by renaming one of the $query variables.

max(id) and limit 10, but use them in different places

I have two tables, posts and sections. I want to get the last 10 posts WHERE section = 1,
but use the 10 results in different places. I make a function:
function sectionposts($section_id){
mysql_set_charset('utf8');
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
$maxpost12 =mysql_query($maxpost1);
while ($maxpost_rows = mysql_fetch_array($maxpost12 ,MYSQL_BOTH)){
$maxpost2 = $maxpost_rows[0];
}
$query = "SELECT * FROM posts WHERE id = $maxpost2";
$query2 = mysql_query($query);
return $query2;
}
$query2 = sectionposts(6);
while ($rows = mysql_fetch_array($query2)){
echo $rows['title'] . "<br/>" . "<br/>";
echo $rows['id'] . "<br/>" . "<br/>";
echo $rows['image_section'] . "<br/>";
echo $rows['subject'] . "<br/>";
echo $rows['image_post'] . "<br/>";
}
How can it take these ten results but use them in different places, and keep them arranged from one to ten.
this was the old case and i solve it but i found another problem, that, if the client had deleted a post as id = 800 "so there aren't id = 800 in DB" so when i get the max id minus $NUM from it, and this operation must be equal id = 800, so i have a programing mistake here, how can i take care of something like that.
function getmax_id_with_minus ($minus){
mysql_set_charset('utf8');
$maxid ="SELECT max(id) FROM posts";
$maxid1 =mysql_query($maxid);
while ($maxid_row = mysql_fetch_array($maxid1)){
$maxid_id = $maxid_row['0'];
$maxid_minus = $maxid_id - $minus;
}
$selectedpost1 = "SELECT * FROM posts WHERE id = $maxid_minus";
$query_selectedpost =mysql_query($selectedpost1);
return ($query_selectedpost);
}
<?php
$ss = getmax_id_with_minus (8);
while ($rows = mysql_fetch_assoc($ss)){
$main_post_1 = $rows;
?>
anyway "really" thanks again :) !
A few thoughts regarding posted code:
First and foremost, you should stop using mysql_ functions as they are being deprecated and are vulnerable to SQL injection.
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
When you SELECT MAX, MIN, COUNT, AVG ... functions that only return a single row, you do not need an ORDER BY or a LIMIT.
Given that you are only asking for the MAX(id), you can save work by combining your queries like so:
SELECT * FROM posts
WHERE id = (SELECT MAX(id) from posts WHERE section_id = $section_id)
If I'm understanding what you're trying to do (please correct me if I'm wrong), your function would look something like:
function sectionposts($section_id) {
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$stmt = mysqli_prepare($link, "SELECT title, id, image_section, subject, image_post FROM posts "
. "WHERE section_id = ? ORDER BY id DESC LIMIT 10");
mysqli_stmt_bind_param($stmt, $section_id);
return mysqli_query($link, $stmt)
}
$result = sectionposts(6);
while ($row = mysqli_fetch_assoc($result)) {
echo $rows['title'] . "<br /><br />";
echo $rows['id'] . "<br /><br />";
echo $rows['image_section'] . "<br />";
echo $rows['subject'] . "<br />";
echo $rows['image_post'] . "<br />";
}
Try this instead, to save yourself a lot of pointless code:
$sql = "SELECT * FROM posts WHERE section_id=$section_id HAVING bar=MAX(bar);"
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo ...;
echo ...;
The having clause lets you find the max record in a single operation, without the inherent raciness of your two-query version. And unless you allow multiple records with the same IDs to pollute your tables, removing the while() loops also makes things far more legible.
Seems like you want to store them in an array.
$posts = array(); //put this before the while loop.
$posts[] = $row; //put this in the while loop

Categories