I have a table containing records created by different users on different dates. My goal is to get the date, users, count of records created by each user, and total count of records per date in this format.
<?php
$q = "SELECT enroledby, enrolment_date, COUNT(enroledby) coun FROM sample_data GROUP BY enroledby";
$result = mysqli_query($db,$q);
while($row = mysqli_fetch_array($result))
{
?>
<th><?php echo $row[0]; ?></th>
<?php
}
?>
The code above is dynamically echoing the users in table header as desired. How do I echo the date, count per user and total count as table data (td) like the above format ?
Thanks.
Related
I am a beginner when it comes to PHP and it is not my specialty, I am rather in the front end and I have a big problem.
I need to edit one of the tables after a guy who doesn't work with our company anymore and it seemed simple to me at first, but I can't find a solution.
I have a table with 4 columns: Date, Full Name, Login, and Points. Records of added points are saved in the database, but each action adding points creates a new record in the database, let's say:
Date
Full Name
Login
Points
04/10/2021
John Kovalsky
koval
10
04/11/2021
John Kovalsky
koval
20
04/12/2021
John Kovalsky
koval
15
The script below works, and I can almost understand the syntax, there is a display limit set here and a table pagination added. The script displays all records in the database.
The problem is that I need exactly the same, but with the sum of the user's points, so that a given user is displayed only once, and in the "Points" column, the sum of all his points is displayed.
I tried with the array_sum () function, but it enumerates all the records in the database for me. The script looks like this:
<?php
$login = $_GET['login'];
$_SESSION["login"] = $login;
include('Pagination.php');
include('config.php');
$limit = 200;
$queryNum = $db->query("SELECT COUNT(*) as ID FROM db_main");
$resultNum = $queryNum->fetch_assoc();
$rowCount = $resultNum['ID'];
$pagConfig = array(
'totalRows' => $rowCount,
'perPage' => $limit,
'link_func' => 'searchFilter'
);
$pagination = new Pagination($pagConfig);
$query = $db->query("SELECT * FROM db_main LIMIT $limit");
echo "<center>";
echo "<table id=\"tabela\" cellpadding=\"2\" border=1>";
echo "<tr>";
echo "<th>".'Date'."</th>";
echo "<th>".'Full Name'."</th>";
echo "<th>".'Login'."</th>";
echo "<th>".'Points'."</th>";
echo "</tr>";
echo "</tr>";
if($query->num_rows > 0){
?>
<?php
while($r = $query->fetch_assoc()){
echo "<tr>";
echo "<td>".$r['Date']."</td>";
echo "<td>".$r['Full_name']."</td>";
echo "<td>".$r['Login']."</td>";
echo "<td>".$r['Points']."</td>";
echo "</tr> </center>";
}
echo $pagination->createLinks();
}
?>
Please help, I have no idea how to do it. I will be very grateful for your help and hints.
You could do it by using a different query.
First, get all unique users.
$db->query("SELECT COUNT(DISTINCT(Full_name)) as ID FROM db_main");
Now get the collected data for each user.
$db->query("SELECT MAX(Date) AS Date, Full_name, Login, SUM(Points) AS Points FROM db_main GROUP BY Full_name LIMIT $limit");
Using the GROUP option will make sure you get one row per user.
The SUM will give you the amount of all the user's points.
The MAX(Day) will return user's the last day field.
There are two assumptions here, that the login is always the same for the user, and that the Points field is numeric and not a string.
I have two tables one having employee name, employee id and another table tblleaves having empid,Leave_Date, fromDate, toDate, Description.
If user choose one day leave it stores the date value to Leave_Date and if user choose multiple days it store value of from date and to date.
Now I want the monthly report of employees. In this page I want an employee name, Leave Days and Leave Dates. I tried codes but I got employee name repeatedly because they apply many leaves in that month i want to display employee name one time.
<?php
if(isset($_POST['apply'])){
$ym=$_POST['month'];
list($Year, $Month) = explode("-", "$ym", 2);
$sql = "SELECT distinct tblleaves.id as lid,tblemployees.FirstName,tblemployees.LastName,tblemployees.EmpId,
tblemployees.id,tblleaves.LeaveType,tblleaves.PostingDate,
tblleaves.Leave_Date from tblleaves join tblemployees on tblleaves.empid=tblemployees.id
WHERE YEAR(Leave_Date) = 2019 AND MONTH(Leave_Date) = 6";
echo $sql;
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<tr>
<td> <?php echo htmlentities($cnt);?></td>
<td><?php echo htmlentities($result->FirstName);?> <?php echo htmlentities($result->LastName);?></td>
<td><?php ?></td>
<td><?php $result->Leave_Date?></td>
<?php $cnt++;}}}?>
I want employee monthly leave report
employee name Leave Days Leave Dates
KrishnanR 3 12-06-2019, 13-06-2019, 14-06-2019
Really that sort of formatting should be done in the report itself by having a band that occurs once per emplyee and shows the name and then within band show all the records for that employee.
However you can get a dataset containing the example result you posted by using the MySQL function GROUP_CONCAT().
The following code will give you three columns, FirstName, LastName and leave_dates with one row per employee. The leave_date column will contain all their tblleaves.Leave_Date values, separated by a comma and a space (or whatever appears after the key word SEPARATOR.
You won't need the DISTINCT
SELECT
tblemployees.FirstName,
tblemployees.LastName,
count(tblleaves.empid) as Leave_Days,
GROUP_CONCAT( tblleaves.Leave_Date SEPARATOR ', ' ) AS leave_dates
FROM
tblleaves
JOIN tblemployees
ON tblleaves.empid = tblemployees.id
WHERE YEAR(Leave_Date) = 2019
AND MONTH(Leave_Date) = 6
GROUP BY tblemployees.EmpId
i have a database with 2 different tables
One table (players) contain a column nammed "totaldeplata" that contains numbers (price)
Other table (vanzari) contain a column like the first one nammed "totaldeplata" it hase the same value inside numbers (the price)
i manage to display the sum of all column for each table like this:
<div align="right"> Total Comenzi luna curenta: <i><strong>
<?php
$query = "SELECT * FROM vanzari WHERE MONTH(datainregistrarii) =
MONTH(CURRENT_DATE())";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['totaldeplata'];
}
echo $qty;
?></strong> </i> Lei
</div>
But this, display only the sum of one table, so i have to write the same code to display the sum of other column in the secound table (in this case the players table)
I need to sum all the numbers from columns "totaldeplata" from tables: vanzari and players, and display them as one number (to sum all the numbers and display them)
Actualy Sum numbers from columns "totaldeplata" from both tables "vanzari" and "players" and display them.
Any ideea how to do that? :)
SELECT (SELECT SUM(field1) FROM table1) + (SELECT SUM(field2) FROM table2) as result
According to your above code and table name.
<?php
$query = "SELECT (SELECT SUM(totaldeplata) FROM vanzari) + (SELECT SUM(totaldeplata) FROM players) as result";
$query_run = mysql_query($query);
$row = mysql_fetch_assoc($query_run);
$sum = $row['result'];
echo "sum of two different column from two tables : "+ $sum;
?>
i have project at university ,where one requirement is student have to applied to the course posted by various institution.
for eg. if institute provide mechanical, chemical courses.and if number of student applied for mechanical course.
and my question is i need to count how many people applied for mechanical course. and show this count in (UI)Frontend part.
this is query i have written to retrieve students who applied for course.
$q="select *
from students
where student_id in (
select applied_stdid
from applicants
where a_subjectid=".$_GET['id']." )";
and the code which i have written to find count and display is------>
<?php
$count=0;
while($row=mysql_fetch_array($res))
echo '<tr> <td width="10%">'.$count.'
<td width="50%">'.$row['student_fnm'].'
<td width="30%">Student Information
';
$count++;
}
echo"count is".$count;
?>
above code is fine i m able to get the count but i have to show the count infront of course like mechanical-- 20 student applied.i have to show this count in another(main page)page.the count which i m getting i have to show this in manin page
I Created a function for you it'll solve your issue. Here is my code:
<?php
//you can name this file as functions.php
function fetchcount() {
$sql = "SELECT * from applicants WHERE a_subjectid='1'";
// eg. 1 for (mechanical) but you have to create individual function for all the courses
$query = mysql_query($sql);
while ($row = mysql_fetch_object($query)) {
$totlal=mysql_num_rows($query );
}
return $totlal;
}
?>
In Your main file where you want to print the count. just do this:
require_once 'functions.php';
$res = fetchcount(); /
echo "count is".$res; // put it anywhere you want
This question already has answers here:
Rank function in MySQL
(13 answers)
Closed 8 years ago.
I have a text based mafia game and I am selected some GameRecords. The game records are all defined in the "users" table. For this example I am using "totalcrimes". I need to select all the rows from the users table and order it by totalcrimes and then find out which row each specific user is that is viewing the page.
If I was the user that was "ranked" 30th it would echo "30". The code I use to find the top 5 is here however I need to expand on it:
<?php
$i = 0;
$FindCrimes = mysql_query("SELECT * FROM players WHERE status='Alive' AND robot = 0 ORDER BY `totalcrimes` DESC LIMIT 5");
while($Row = mysql_fetch_assoc($FindCrimes)){
$Username = $Row['playername'];
$TotalCrimes = number_format($Row['totalcrimes']);
$i++;
echo "
<tr>
<td bgcolor='#111111' width='5%'>$i</td>
<td bgcolor='#111111' width='50%'><a href='viewplayer?playerid=$Username'>$Username</a></td>
<td bgcolor='#333333' width='45%'>$TotalCrimes</a></td></td>
</tr>
";
}
?>
I am going to assume that you already have a variable set to hold the current users ID number and total crimes, so in this case I will use $user as my variable.
Change yours to fit.
Now, I see 2 instances in which you could mean as your post wasn't very specific, so I will address both.
To show the number at the top of the page, you would use something like;
<?php
$sql = "SELECT * FROM `players` WHERE `totalcrimes` > '{$user['totalcrimes']}'";
$run = mysql_query($sql);
$rank = mysql_num_rows($run) + 1;
echo 'Your rank: ' . $rank;
Other than that, I see it's possibly being used to highlight your row, so something like this would suffice;
<?php
$i = 0;
$FindCrimes = mysql_query("SELECT * FROM players WHERE status='Alive' AND robot = 0 ORDER BY `totalcrimes` DESC LIMIT 5");
while($Row = mysql_fetch_assoc($FindCrimes))
{
$Username = $Row['playername'];
$TotalCrimes = number_format($Row['totalcrimes']);
$i++;
$primary = '#111111';
$secondary = '#333333';
if ($Row['id'] == $user['id'])
{
$primary = '#222222';
$secondary = '#444444';
}
echo "<tr>
<td bgcolor='$primary' width='5%'>$i</td>
<td bgcolor='$primary' width='50%'><a href='viewplayer?playerid=$Username'>$Username</a></td>
<td bgcolor='$secondary' width='45%'>$TotalCrimes</a></td></td>
</tr>";
}
If neither of those give your requirements, please comment and I'll edit to suit.
edit: I've worked on games for a few years - care to share the link to yours?
This can do the trick
SELECT COUNT(*)+1 as rank
FROM users
WHERE totalcrimes > (SELECT totalcrimes
FROM users
WHERE user_id='12345' AND status='Alive' AND robot='0');
So it counts all rows with greater totalcrimes than selected user (in this example I have used user_id column and some id 12345), than adds 1 on that sum and returns as rank value.
Course, modify WHERE clause inside the brackets to make it work for you.
I assumed that table name is users and user's id is integer user_id.
Test preview (Navicat Premium):
What this query does? It returns number of selected rows + 1 as rank column, from the table users where totalcrimes is greater than totalcrimes of some user. That user's totalcrimes is selected by another query (by its user_id). If you have multiple users with same totalcrimes value, this query will return same rank for all of them.