Number of entries in DB PHP - php

I am creating a function to show how many users are online now. This is based on who has opened a page within the last 5 min. Each page load is saved to my DB, below:
At the moment I have the following code
$query = mysql_query("SELECT user_id, timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
$onlineUsers = mysql_num_rows($query);
This is simply totalling the number of rows, how can I do this so it only counts a user_id once? (so in the above database snippet it should be 2 not 5)

use DISTINCT keyword
$query = mysql_query("SELECT DISTINCT(user_id), timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
$onlineUsers = mysql_num_rows($query);

Since mysql_* is deprecated (php 5 onward) and removed in (php 7). So a mysqli_* example is here:-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','username','password','db name');//change credentials here
$online_users = array();
if($conn){
$query = mysqli_query($conn,"SELECT DISTINCT(user_id), timestamp,page FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
if($query){
while($row = mysqli_fetch_assoc($query)){
$online_users[] = $row;
}
}else{
echo "query error:-".mysqli_error($conn);
}
}else{
echo "db connection error:-".mysqli_connect_error();
}
?>
<table>
<tr>
<thead>
<th>User Id</th>
<th>timestamp></th>
<th>Page Visited</th>
</thead>
</tr>
<tbody>
<?php foreach($online_users as $online_user){?<
<tr>
<td><?php echo $online_user['user_id'];?></td>
<td><?php echo $online_user['timestamp'];?></td>
<td><?php echo $online_user['page'];?></td>
</tr>
<?php }?>
</tbody>
</table>
Note:- If you want to show online user name also then you have to do JOIN query.
change table code accordingly.
It's a sample code. modify it accordingly.

You may use group by, e.g
SELECT user_id, timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute) group by user_id;

Related

how can i display all of the results from my table where the column (date and time) has the the same date and time

You see in my table in the column (date and time) : i have multipes same result date and time.
how can i display all of the results from my table where the column (date and time) has the the same date and time.
how can i count in every table the result of the column price that has the same date and time.
This is my php code:
<tabl>
<?php
function connectDb($username,$password,$hostname,$dbname)
{
$conn=mysql_connect("$hostname","$username","$password") or die(mysql_error());
$db=mysql_select_db("$dbname",$conn) or die(mysql_error());
}
connectDb('root','root','localhost','vetemenstdb');
// end connect db
// start display result
function select()
{
$tableName = 'venteJour';
$query = "SELECT * FROM $tableName";
$sql = mysql_query($query);
while($row = mysql_fetch_assoc($sql))
{
$id = $row['id'];
$Name = $row['nomDuProduit'];
$price = $row['PrixVenteFinal'];
$quantity = $row['QuantityVendue'];
$dateAndTime = $row['dateAndTime'];
echo"
<tr>
<td>$id</td>
<td>$Name</td>
<td>$price</td>
<td>$quantity</td>
<td>$dateAndTime</td>
</tr>";
}
}
select();
//end display result
?>
</table>
What do you mean has the same date and time?
Select DISTINCT dateAndTime from tablename
After doing the same queries in other tables you simply
if ($dateAndTime1 != $dateAndTime2)
return false;
or you could use
array_intersect($array1, $array2)
if you don't want to sort arrays but just want to check equality regardless of value order use http://php.net/manual/en/function.array-intersect.php
Updated:
select dateandtime, count(*) as c from table
group by dateandtime having c > 1

PHP Row and Column Count

I was wondering if you guys can help me, I am pulling Data from a mysql database and I am looking to have the content echo in rows, like a shopping cart. Below is the code I am using. The Code is working flawlessly, but I don't know how to add the Row Count to it and Column Count to it.
Working Code:
<?
$dmealh = mysql_query("select count(*) from jobs_cart where mid='$mid'");
$jmealh = mysql_fetch_array($dmealh);
if ($jmealh[0]) {
$dmealh = mysql_query("select * from jobs_cart where mid='$mid' order by date desc, time desc");
while ($jmealh = mysql_fetch_array($dmealh)) {
echo "$id - $jmealh[name] - $jmealh[meals]";
}
}
?>
This is what I want the Data to look like:
Row Count- Name - Meal Count
1 - Greg - 3
2 - Mike - 4
3 - Tomm - 1
8 Meals Total
Just use a basic counter to keep track of what row you are on and use another variable to add up the meal count as you loop through your results and then echo out the final count. Throw it all into a table and you're set.
<?php
$dmealh = mysql_query("select count(*) from jobs_cart where mid='$mid'");
$jmealh = mysql_fetch_array($dmealh);
if ($jmealh[0]) {
$dmealh = mysql_query("select * from jobs_cart where mid='$mid' order by date desc, time desc");
$total_meals = 0; // Keep track of the total number of meals. Start at zero.
$row = 1; // Keep track of current row. Start at one.
?>
<table>
<?php
while ($jmealh = mysql_fetch_array($dmealh)) {
?>
<tr>
<td><?php echo $row; ?></td>
<td><?php echo $jmealh['name']; ?></td>
<td><?php echo $jmealh['meals']; ?></td>
</tr>
<?php
$total_meals += $jmealh[meals]; // Add to total meals
$row++; // Increase row count
}
?>
<tr>
<td></td>
<td></td>
<td><?php echo $total_meals; ?> Meals Total</td>
</tr>
</table>
}
Don't use mysql_* functions...they're deprecated (note the red box near the top).
Where does $mid come from? Make sure to escape your database inputs to prevent SQL injection.
You're doing extra work by first querying to see if any rows are returned. Just do the SELECT query and while loop. If no rows are returned, the loop will not execute.
You should be using an HTML table to display this data. Use PHP variables to keep track of your sums.
A crude example:
$mid = mysqli_real_escape_string($mid);
$rows = $total = 0;
$result = mysqli_query("SELECT name, meals FROM jobs_cart WHERE mid = '$mid' ORDER BY date DESC, time DESC");
echo '<table>';
while ($row = mysqli_fetch_assoc($result)) {
$rows++;
$total += $row['meals'];
echo '<tr><td>'. $rows .'</td><td>'. $row['name'] .'</td><td>'. $row['meals'] .'</td></tr>';
}
echo '<tr><td> </td><td> </td><td>'. $total .'</td></tr></table>';

PHP Datetime query how?

Sorry my English a little,
My date column is 1375801584 valuable epoch format.
I wanna only select now and next time records, i want hide history times record.
eg: 19:45 and later.
<?php
$sql = mysql_query("select tarih from table where tarih < '$date' order by tarih ASC");
while($r = mysql_fetch_assoc($sql)){
?>
<tr><td><?php echo date("Y-m-d", $r['tarih']); ?></td>
<td><?php echo date("H:i", $r['tarih']); ?></td></tr>
<?php
}
?>
You close. Your current query is selecting older records (<). Try using >=:
$sql = mysql_query("select date from table where date >= '$date;' order by date ASC");

Using PHP to Output MySQL Query Where COUNT(*) is Used [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
mysql count into PHP variable
I have the following query that returns successfully when run from MySQL command prompt:
SELECT `from_email`, COUNT(*)
FROM `user_log`
GROUP BY `from_email`
ORDER BY COUNT(*) DESC
This query returns a result set that has the following columns
`from_email` | COUNT(*)
My question is, how do I go about iterating through the result sets and outputting the results. I have my table formatted I just need from_email in one table cell and the associated COUNT in another for each record.
Thanks in advance
add an ALIAS on it
SELECT `from_email`, COUNT(*) AS totalCount
FROM `user_log`
GROUP BY `from_email`
ORDER BY totalCount DESC
and you can now fetch the value
$row["from_email"]
$row["totalCount"]
Following is the code for connect to database and retrieve the result and display in table.
<?
$conn = mysqli_connect("localhost", "root","root", "test");
$query="SELECT `from_email`, COUNT(*) AS emailCount FROM `user_log` GROUP BY `from_email` ORDER BY COUNT(*) DESC";
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH))
{
$table[] = $row;
}
}
?>
<table border="1">
<tr>
<td width="200">From Email</td>
<td width="50">Count</td>
</tr>
<?
if($table){
for($i=0;$i<count($table);$i++){
?>
<tr>
<td><?=htmlentities($table[$i]["from_email"])?> </td>
<td><?=htmlentities($table[$i]["emailCount"])?> </td>
</tr>
<?
}
}
?>
</table>

How to calculate the SUM of a temp column created from a query

My query is working, but I need to calculate the total of a column which is created from the query, I am using a normal php script to add the value (in money) of the accumulated working hours, this also works perfectly. But how do I then get the Sum or total of this column, which should give me a single figure, used in an echo line as "....accumulated salary for the period is _", see second last line from my script.
Following is a snipped of the script:
<?php
include("../xxx");
$cxn = mysqli_connect($host,$user,$password,$dbname)
or die ("Couldn't connect to server.");
$query = "SELECT
ea.`employee_id`,
e.`employee_surname`,
e.`employee_first_name`,
e.`employee_second_name`,
e.`employee_salary`,
FORMAT((IF((SUM(ea.`empl_attendance_total`))<180,(SUM(ea.`empl_attendance_total`)),180)),1) AS nt,
FORMAT((IF(((SUM(ea.`empl_attendance_total`))-(SUM(CASE WHEN WEEKDAY(ea.empl_attendance_date) > 5 THEN ea.empl_attendance_total END)))<=180,
0,(IF(((SUM(ea.`empl_attendance_total`))-(SUM(CASE WHEN WEEKDAY(ea.empl_attendance_date) > 5 THEN ea.empl_attendance_total END)))>180,
((SUM(ea.`empl_attendance_total`))-(SUM(CASE WHEN WEEKDAY(ea.empl_attendance_date) > 5 THEN ea.empl_attendance_total END)))-180,
0)))),1) AS ot,
FORMAT((IF((SUM(ea.`empl_attendance_total`))>180,
IF((SUM(ea.`empl_attendance_total`))-180>=(SUM(CASE WHEN WEEKDAY(ea.empl_attendance_date) > 5 THEN ea.empl_attendance_total END)),
(SUM(CASE WHEN WEEKDAY(ea.empl_attendance_date) > 5 THEN ea.empl_attendance_total END)),(SUM(ea.`empl_attendance_total`))-180),
0)),1) AS st,
FORMAT((SUM(ea.`empl_attendance_total`)),1) AS total
FROM
empl_attendance ea
JOIN
employee e
ON ea.`employee_id` = e.`employee_id`
WHERE ea.`empl_attendance_date` BETWEEN '$start_date' AND '$end_date'
GROUP BY `employee_id`";
$result = mysqli_query($cxn,$query)
or die ("Couldn't execute query.");
$total_salary = 0;
/* Displays items already in table */
echo "<table><br>
<tr>
<th>Empl No</th>
<th>Empl Name</th>
<th>N/T (1.0)</th>
<th>O/T (1.5)</th>
<th>S/T (2.0)</th>
<th>Total Hrs</th>
<th>Est Salary</th>
</tr>";
while($row = mysqli_fetch_assoc($result))
{
extract($row);
$sal = ((($employee_salary/180)*$nt)+((($employee_salary/180)*$ot)*1.5)+((($employee_salary/180)*$st)*2));
$salary = number_format($sal, 2, '.', ',');
// add this salary to the total
$total_salary += $sal;
echo "<tr>\n
<td>$employee_id</td>\n
<td>$employee_surname, $employee_first_name $employee_second_name</td>\n
<td>$nt</td>\n
<td>$ot</td>\n
<td>$st</td>\n
<td>$total</td>\n
<td>R $salary</td>\n
</tr>\n";
}
// change the format of the salary variable
$acc_sal = number_format($total_salary, 2, '.', ',');
echo "</table><br>";
echo "Accumulated Salary for the selected period is<b> R $acc_sal<b>";
?>
A fairly easy way of doing this would be to define a new variable (eg $total_salary) before the while loop and adding each salary to it.
So you would have (code is truncated somewhat):
...
$total_salary = 0;
while($row = mysqli_fetch_assoc($result))
{
extract($row);
$sal = ((($employee_salary/180)*$nt)+((($employee_salary/180)*$ot)*1.5)+((($employee_salary/180)*$st)*2));
$salary = number_format($sal, 2, '.', ',');
// add this salary to the total
$total_salary += $sal;
echo "... row markup ...";
}
echo "</table><br>";
echo "<b> Accumulated Salary for the selected period is $total_salary<b>";
P.S.: That's one awesome query!!! :)
Since you're only using GROUP BY on one column, check out the WITH ROLLUP option, which will return you one more row from the database.
If you do this, leave a huge comment in your code, because future developers may not be expecting that extra row.

Categories