Currently, I'm stuck here in this part of my program. I want to fetch the data from the table I created which named enrollment_confirm. I want to add the total of female students and male students then the total combined of the two gender.
Here is my code so far in MySQL.
include_once('samplesf1-db.php');
$pdo = Database::connect();
$query1 = "SELECT
COUNT(CASE WHEN UPPER(Gender) = 'TOTAL MALE' THEN 1 END) Male,
COUNT(CASE WHEN UPPER(Gender) = 'TOTAL FEMALE' THEN 1 END) Female,
COUNT(CASE WHEN Gender IS NULL THEN 1 END) 'Not Assigned',COUNT(LRN) AS 'COMBINED' FROM enrollment_confirm";
$result = mysqli_query($con, $query1);
while($row = mysqli_fetch_array($result)){
echo $row['Gender'];
}
Database::disconnect();
?>
Is there anything
So, when I run the code. This is what it says.
enter image description here
Can you tell me if I did something wrong in the query?
Related
Right, I'll be specific as possible here - I'll first outline what I need, then what I've done - I can usually plod on with these so bear in mind I'm only asking as my brain is fried!
I have a table in my database - we only need to know it has these fields (gender - male or female, layout - 0 or 1)
I want to find the most used layout (0 or 1) for males - I've done this by:
$result = mysqli_query($conn, "SELECT layout,COUNT(*) as num
FROM style where gender = 'male' group by layout order by num DESC
LIMIT 1" );
I want to check if the returned result (so most frequent) is 0 or 1, so i can use that in an IF statement (so far i'm just using an echo to test)
I'm sorry if this if very trivial, or if i've missed anything out - if you need any extra info let me know.
Your code is fine for determining whether males prefer layout 0 or 1, you just need to look at the output value:
$result = mysqli_query($conn, "SELECT layout, COUNT(*) as num
FROM style
WHERE gender = 'male'
GROUP BY layout
ORDER BY num DESC
LIMIT 1" );
$row = mysqli_fetch_assoc($result);
if ($row['layout'] == 0)
echo "males prefer layout 0";
else
echo "males prefer layout 1";
PHP:
$DTB->new mysqli($Mysql_Server,$Mysql_User,$Mysql_Password,$Mysql_Database);
$Layout0=($DTB->query("SELECT layout FROM style WHERE gender ='male' AND layout=0 "))->num_rows;
$Layout1=($DTB->query("SELECT layout FROM style WHERE gender ='male' AND layout=1 "))->num_rows;
IF ($Layout0>$Layout1){
...
}
$resultResource = mysqli_query($conn, 'SELECT layout,COUNT(*) as num FROM style where gender = "male"');
while ($row = mysqli_fetch_assoc($resultResource)){
$maleCount = $row['num'];
}
$resultResource = mysqli_query($conn, 'SELECT layout,COUNT(*) as num FROM style where gender = "female"');
while ($row = mysqli_fetch_assoc($resultResource)){
$femaleCount = $row['num'];
}
if ($femaleCount > $maleCount){
//more females in database
}elseif($femaleCount < $maleCount){
//more males in database
}else{
//same amount of both;
}
So this is the structure of my MySQL table that I wanna work this out with:
ID type category_id amount
12 Expense 3 963.39
13 Expense 5 1200.50
14 Expense 3 444.12
15 Expense 5 1137.56
..............................
Desired output:
1407,41 (for category_id = 3)
2338,06 (for category_id = 5)
....... (and for other category_id)
What I get now:
1407,41 (only for category_id = 3)
My query does not add or display the sum of other category_id.
This is the query I am trying:
$query = "SELECT SUM(amount) AS TotalAmount FROM spendee WHERE type = 'Expense'
group by category_id having count(*) >1 ";
$expense_query = mysqli_query($connection, $query);
$expense_count = mysqli_fetch_array($expense_query);
echo $expense_count[0];
Been stuck with this for the last couple of days. Any help is very much appreciated. Thank you!
You're only calling mysqli_fetch_array() once. You need to call it in a loop to get all the totals. You should also include the category ID in the SELECT list.
$query = "SELECT category_id, SUM(amount) AS TotalAmount FROM spendee WHERE type = 'Expense'
group by category_id having count(*) >1 ";
$expense_query = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($expense_query)) {
echo "{$row['TotalAmount']} (for category_id = {$row['category_id']}<br>\n";
}
The query here works. It's just that you only select the first result from the $expense_count variable. $expense_count[1] will return the second category listed, $expense_count[2 will return the third one, ect...
Try echo implode(" <br>", $expense_count);
Have a nice day.
Sorry i am new to this. Just trying to learn. I am trying to conditionally count the number of times a particular condition occurs in SQL, using the case and count functions. This counts the number of males/females stored in eeg table. Here is my SQL query.
SELECT COUNT(CASE WHEN `Gender` = 'Male' THEN 1 END),
COUNT(CASE WHEN `Gender` = 'Female' THEN 1 END)
FROM `eeg`
This outputs the data when i run the query on the mysql backend (phpmyadmin), but in my php file, I get an "Undefined Index" error for those 2 rows. All othjer rows are perfectly okay. I do not know how to output those particular set of data to a variable.
Here is the SQL query (in full) in the php file:
$result = mysql_query("SELECT MONTH(ScanDate), YEAR(ScanDate),
COUNT(Investigation),
COUNT(CASE WHEN `Gender` = 'Male' THEN 1 END),
COUNT(CASE WHEN `Gender` = 'Female' THEN 1 END),
SUM(InvestigationAmount), SUM(AmountDue)
FROM eeg
WHERE Investigation = '{$investigation}'
AND ScanDate BETWEEN '{$ScanDate1}'
AND '{$ScanDate2}'");
Here is the while loop (in full):
while($row=mysql_fetch_array($result)){
$month_doe=$row['MONTH(ScanDate)'];
$year_doe=$row['YEAR(ScanDate)'];
$si=$row['COUNT(Investigation)'];
$male=$row["COUNT(CASE WHEN 'Gender' = 'Male' THEN 1 END)"];
$female=$row["COUNT(CASE WHEN 'Gender' = 'Female' THEN 1 END)"];
$sum_investigation=number_format($si);
$sia=$row['SUM(InvestigationAmount)'];
$sum_investigationamount=number_format($sia);
$srd=$row['SUM(AmountDue)'];
$sum_rebatedue=number_format($srd);
}
Thank you for your help. Been literally pulling my hair out, but love to learn and improve. And yes, mysql_query is depreciated :D
screenshots below:
Code screenshot
Use an alias for the expressions and use the alias to access the results of the expressions from php:
$result = mysql_query("SELECT MONTH(ScanDate) as sdyear,
YEAR(ScanDate) as sdmonth,
COUNT(Investigation) as investigation,
COUNT(CASE WHEN `Gender` = 'Male' THEN 1 END) as MaleCount,
COUNT(CASE WHEN `Gender` = 'Female' THEN 1 END) as FemaleCount,
SUM(InvestigationAmount) as investigationamount,
SUM(AmountDue) as amountdue
FROM eeg
WHERE Investigation = '{$investigation}'
AND ScanDate BETWEEN '{$ScanDate1}'
AND '{$ScanDate2}'");
while($row=mysql_fetch_array($result)){
$month_doe=$row['sdmonth'];
$year_doe=$row['sdyear'];
$si=$row['investigation'];
$male=$row["MaleCount"];
$female=$row["FemaleCount"];
$sum_investigation=number_format($si);
$sia=$row['investigationamount'];
$sum_investigationamount=number_format($sia);
$srd=$row['amountdue)'];
$sum_rebatedue=number_format($srd);
}
I would use this approach for every field that is an expression (the other sum() fields in the above query).
I have a table called "guesses" that stores peoples guesses whether a baby is a boy or a girl. Those are the two possible things in the "sex" column (i.e. "boy" or "girl).
There are 4 guesses in the table for this poolid. So if I run this code below...
$sql = "SELECT
FROM guesses
WHERE poolid = '$poolid'
ORDER BY $sort, createddate";
$getguesses = mysqli_query($connection, $sql);
if (!$getguesses) {
die("Database query failed: " . mysqli_error($connection));
} else {
//Get total number of guesses
$numguesses=mysqli_num_rows($getguesses);
echo "NUMGUESSES: $numguesses";
while ($row = mysqli_fetch_array($getguesses)) {
//code to grab other info about guesses, not relevant, works fine
}
}
It outputs
NUMGUESSES: 4
And also spits out 4 lines (one for each guess) with other info that isn't relevant.
I would like to count the total number of girl guesses vs. boy guesses, for use later in a pie chart. So I did the following...
$sql = "SELECT *, COUNT(CASE WHEN `sex` = 'girl' then 1 ELSE NULL END) as 'totalgirls', COUNT(CASE WHEN `sex` = 'boy' then 1 ELSE NULL END) as 'totalboys'
FROM guesses
WHERE poolid = '$poolid'
ORDER BY $sort, createddate";
$getguesses = mysqli_query($connection, $sql);
if (!$getguesses) {
die("Database query failed: " . mysqli_error($connection));
} else {
//Get total number of guesses
$numguesses=mysqli_num_rows($getguesses);
echo "NUMGUESSES: $numguesses";
while ($row = mysqli_fetch_array($getguesses)) {
echo "GIRLS:". $row['totalgirls'];
echo "BOYS:". $row['totalboys'];
//code to grab other info about guesses, not relevant
}
}
This outputs
NUMGUESSES: 1
GIRLS: 4
BOYS: 0
And also spits out ONLY ONE line (for only one of the four existing guesses)
All four guesses are girls, so the GIRLS total and the BOYS total are correct. But why is it only seeing NUMGUESSES as 1 now? It should be 4 and should show 4 lines of guesses.
Something with the COUNT() is throwing something off. Any ideas?
You're asking mysql to count, so it outputs one line ; )
Try this instead:
$sql = "SELECT COUNT(*), SUM(CASE WHEN `sex` = 'girl' then 1 ELSE 0 END) as.....
Beware of including NULL values in a count!
Currently for a football league, standings are calculated with their own table so I have to manually input/edit Wins, losses, ties, PF and PA. I want to generate this dynamically based on the results of the schedule table which is where scores are recorded.
So I have the following ugly code:
$teamidsql = mysql_query("select team_id, count(team_id) as numteams from team WHERE league_id=$currentleague AND team_div='$div'");
$teamid = mysql_result($teamidsql,0,"team_id");
$numteams = mysql_result($teamidsql,0,"numteams");
$endteams = $teamid+$numteams;
while($teamid < $endteams)
{
$result2=mysql_query("select team_name, team_div,
count(case when (schedule_team1_id = $teamid and schedule_team1_score > schedule_team2_score) or (schedule_team2_id = $teamid and schedule_team2_score > schedule_team1_score) then 1 else NULL end) as wins,
count(case when (schedule_team1_id = $teamid and schedule_team1_score < schedule_team2_score) or (schedule_team2_id = $teamid and schedule_team2_score < schedule_team1_score) then 1 else NULL end) as losses,
count(case when schedule_team1_score = schedule_team2_score then 1 else NULL end) as ties,
sum(case when schedule_team1_id = $teamid then schedule_team1_score else schedule_team2_score end) as pf,
sum(case when schedule_team1_id <> $teamid then schedule_team1_score else schedule_team2_score end) as pa
from schedule, team
where team_id = $teamid AND team.team_div='$div' AND schedule_week >= 1 and schedule_week <= 13 and schedule.league_id = $currentleague and (schedule_team1_id = $teamid or schedule_team2_id = $teamid)") or die(mysql_error());
$t_n = mysql_result($result2,0,"team_name");
$t_w = mysql_result($result2,0,"wins");
$t_l = mysql_result($result2,0,"losses");
$t_t = mysql_result($result2,0,"ties");
$t_pf = mysql_result($result2,0,"pf");
$t_pa = mysql_result($result2,0,"pa");
echo "<tr>";
echo "<td>$t_n</td><td>$t_w</td><td>$t_l</td><td>$t_t</td><td>$t_pf</td><td>$t_pa</td>";
echo "</tr>";
$teamid++;
}
Which currently generates the following html:
http://i.stack.imgur.com/sBVfM.png
My question is how can I sort it? The old table was easy, but I have no idea how I would take this individual data I'm calculating and then sort it via wins, losses, ties, pf then pa.
datatables is the fastest solution to this problem. Give the table a class, call datatabes in the onload, and it will render javascript sorting based on the contents of the html.
http://datatables.net/