I have a Log in PHP which shows all the things I've done.
the construction is like:
Date -- Things done -- Hours
I figured how to show all the info in a table. But I want to have a total hours in the bottom which calculated all the hours of the database.
I'm adding every day a new log (what I've done that day). But I wanna know how I can do this. I've been searching for a while now, without success..
I hope anyone can help me.
Thanks in advance.
This is how I display my code(short version):
<tr>
<td class="date"><?php echo $row['Date'] ?></td>
<td><?php echo $row['Detail'] ?></td>
<td><?php echo $row['Hours'] ?></td>
</tr>
So for clarification:
I make a new td which echo's the total hours by adding all the hours.
So if my hours are 8 + 8 + 8 + 8 + 4 + 5 in the hours table it will be shown as:
Total hours: 41 hours
To display the total sum of hours, you do this:
$db = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_DATABASE );
$sql = 'SELECT SUM( `Hours` ) AS `total` FROM `table_name`';
$res = $db->query( $sql ) or die( 'MySQL error ' . $db->error );
$row = $res->fetch_assoc();
echo 'Total: ' . $row['total'];
If date is of typ datetime/date/timestamp you can get the total for every day like this (If the date is of type date, you do not need DATE(date)):
$sql = 'SELECT DATE(`date`) AS `day`, SUM(`Hours`) as `total` '
. 'FROM `table_name` GROUP BY DATE(`date`) ORDER BY `date`';
$res = $db->query( $sql ) or die( 'MySQL error ' . $db->error );
while( $row = $res->fetch_assoc() )
echo $row['day'] . ' has ' . $row['total'] . ' hours' . PHP_EOL;
If date is of typ int or PHP timestamp you can get the total for every day like this:
$sql = 'SELECT DATE( FROM_UNIXTIME(`date`) ) AS `day`, SUM(`Hours`) as `total` '
. 'FROM `table_name` GROUP BY DATE(FROM_UNIXTIME(`date`)) ORDER BY `date`';
$res = $db->query( $sql ) or die( 'MySQL error ' . $db->error );
while( $row = $res->fetch_assoc() )
echo $row['day'] . ' has ' . $row['total'] . ' hours' . PHP_EOL;
Related
I am trying to find if two runners have ever ran in the same race. The two runners are Peter Smith and Diane Peters.
$resultRaceType = mysqli_query($db,"SELECT DISTINCT date,time FROM results where runner = 'Peter, Smith' ");
while($row = mysqli_fetch_array( $resultRaceType ))
{
$resultRaceType1 = mysqli_query($db,"SELECT * FROM results where date = ' " . $row['date'] . " ' and time = ' " . $row['time'] . " ' and runner = 'Diane, Peters'");
while($row1 = mysqli_fetch_array( $resultRaceType1 ))
{
echo "<tr >";
echo "<td>";
echo $row1['date'];
echo " - " . $row1['time'];
echo "</td>";
echo "<tr>";
}
}
The above code works, but only if I limit the first select to LIMIT 50. So I can see that it is timing out. My table has over 100K rows. I know I am doing something wrong but cant see what it is.
Thanks for any help you guy's can give me.
Try:
SELECT a.date, a.time FROM results a
JOIN results b ON (a.date = b.date AND a.time = b.time)
WHERE a.runner='Peter, Smith' AND b.runner='Diane, Peters';
I make an unique id, which contain of CURRENT_DATE and character like :
SELECT CONCAT(DATE_FORMAT(CURRENT_DATE,'%Y%m%d'),'Q',
LPAD(MAX(RIGHT(idreport,3))+1,3,'0'))
FROM record.report
result :
20140723Q001
I want every day it start from 001. So, if the query above is correct I would get result like 20140724Q001 today. But I get a wrong result 20140724Q002.
How to reset 3 digit behind the id if the day change?
complete syntax :
$sql="SELECT CONCAT(DATE_FORMAT(CURRENT_DATE,'%Y%m%d'),'Q',LPAD(MAX(RIGHT(idreport,3))+1,3,'0'))
FROM record.report";
$res=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
$dat1=mysql_fetch_array($res, MYSQL_NUM);
if($dat1 == 0){
$sql = "SELECT DATE_FORMAT(CURRENT_DATE,'%Y%m%d')";
$res1=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
$dat2=mysql_fetch_array($res1, MYSQL_NUM);
// first number
$RegNum = $dat2[0]."Q001";
} else {
$RegNum = $dat1[0];
}
Although we can have a more optimized solution, this should do your job-
SELECT CONCAT(DATE_FORMAT(CURRENT_DATE,'%Y%m%d'),'Q',
LPAD(MAX(RIGHT(CASE WHEN LEFT(idreport,8)=DATE_FORMAT(CURRENT_DATE,'%Y%m%d') THEN idreport ELSE '000' END,3))+1,3,'0'))
FROM record.report;
Incase any query, please let me know.
I want to count a record by current date from different tables and return as one row with different column in the new table. The code will update a record every three hours and insert new record if current date changes. I've current date and time data (2013-05-20 14:12:12) in "created_at" column. Here my current code:
require_once('./db_connect.php');
$dbcon = new db;
//test to see if a specific field value is already in the DB
public function in_table($table,$where) {
$query = 'SELECT * FROM ' . $table . ' WHERE ' . $where;
$result = mysqli_query($this->dbh,$query);
$this->error_test('in_table',$query);
return mysqli_num_rows($result) > 0;
}
//running in background
while (true) {
$select= "SELECT (SELECT CURDATE()) AS time," .
"(SELECT COUNT(tweet_id) FROM tweets WHERE created_at= 'CURDATE() %') AS total_count," .
"(SELECT COUNT(fid) FROM fun WHERE ftime= 'CURDATE() %') AS f_count," .
"(SELECT COUNT(sid) FROM sad WHERE stime= 'CURDATE() %') AS s_count";
$results = mysqli_query( $dbcon, $select );
while($row = mysqli_fetch_assoc($result)) {
$time = $row['time'];
$total = $row['total_count'];
$fcount = $row['f_count'];
$scount = $row['s_count'];
$field_values = 'time = "' . $time . '", ' . 'total_count = ' . $total . ', ' . 'fun_count = ' . $fcount . ', ' . 'sad_count = ' . $scount;
if ($dbcon->in_table('count','time= "' . $time . '"')) {
$update = "UPDATE count SET $field_values WHEN time= '$time'";
mysqli_query( $dbcon, $update );
}
else {
$insert = "INSERT INTO count SET $field_values";
mysqli_query( $dbcon, $insert );
}
}
//update record every 3 hour
sleep(10800);
}
With this code I can't get a count record. The result return | 2013-05-18 | 0 | 0 | 0 |. How can I correct this?
I not familiar with PHP, but you can retrieve the count of all records dated any time today using:
SELECT COUNT(tweet_id)
FROM tweets
WHERE created_at >= curDate()
AND created_at < date_add(curDate(), interval 1 day)
It is equivalent to saying
..
WHERE created_at >= (today at midnight *incusive*)
AND created_at < (tomorrow at midnight *exclusive*)
Update:
The advantage of this method is it is index friendly. While using WHERE DATE(Column) = currDate() works, it can prevent the database from using indexes on that column, making the query slower.
Replace the parts where you have this:
WHERE created_at= 'CURDATE() %'
with this:
WHERE DATE(created_at) = CURDATE()
Your existing WHERE clause is comparing created_at to the string constant CURDATE() %, and they'll never match.
You are comparing against created_at= 'CURDATE() %', which is looking for that exact string, not for the result of a function. If the field created_at is a date, it will never match.
And, you are doing that for all counts.
Okay, so I do understand that if I am running the strtotime function on a day that is the 29th or higher I will incur the February bug and get a result for March instead.
Also I get that if I set the date to Feb 1st, I can avoid the issue.
But here is the problem. I am rolling through the last 12 months of records to generate sales/billing numbers for tracking. How do I ask for all records in February when my loop looks like this?
setlocale( LC_MONETARY, 'en_US' );
$i = 0;
while( $i <= 11 ) {
$select = "SELECT * FROM `my_table` " .
"WHERE YEAR( billing_date ) = '" . date( 'Y', strtotime( -$i . ' month' )) . "' " .
" AND MONTH( billing_date ) = '" . date( 'm', strtotime( -$i . ' month' )) . "'";
$result = mysql_query( $select );
$num_rows = mysql_num_rows( $result );
$sales = 16 * $num_rows;
echo "<p align='center'>";
echo "Sales for " . date( 'M, Y', strtotime( '-' . $i . ' month' ) ) .
" " . money_format( '%i', $sales );
echo "</p>";
$i++;
}
How do I avoid the February bug? Would it be an if statement? What would that look like?
Here is a pure SQL solution (if I correctly understand the scenario):
SELECT
YEAR(billing_date) AS billing_year,
MONTH(billing_date) AS billing_month,
16 * COUNT(*) AS sales /* Why x16?!!! */
FROM my_table
GROUP BY YEAR(billing_date), MONTH(billing_date)
This will calculate the sales directly in SQL, so in PHP you just need a display loop.
How do I ask for all records in February...
SELECT * FROM table WHERE MONTH(billing_date) = 2
February bug? It's not a bug. Normalizing dates is a (useful) feature! :-)
If you want the last day in February, ask for the 0th of March.
I don't know the "february bug", but you could try to use MySQL to subtract 1 month. Check
SELECT DATE_SUB(billing_date, INTERVAL 1 MONTH) FROM my_table
=> Manual
I am trying to output some minutes 7 days after a meeting has taken place. I have inserted in the following code only to get a fatal error message.
<?php
$id = $_GET['meeting_id'];
$from = date( 'Y-m-d', strtotime( $row['date_update'] . '-7 days' ) );
$result = $this->db->get ('SELECT * FROM Meetings INNER JOIN Minutes ON Minutes.meeting_id = Meetings.meeting_id WHERE Rooms.date >= "' . $from . '" AND Rooms.date <= NOW() AND Minutes.meeting_id = $id')
or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo '<h3>There Arent Any Minutes For This Meeting Yet</h3>';
} else {
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><br/>" .'Title: '. $info['title']." </td>";
echo "<td><br/><br/>" .'Subject: '. $info['subject']. "</td>";
echo "<td><br/><br/>" .'Next Subject: '. $info['next_subject']."</td>";
echo '<br/><br/>Attendees';
echo ' | Apologies';
}
}
echo "</tr>";
echo "</table>";
?>
the error message i am getting is as follows:
Fatal error: Using $this when not in object context in E:\webareas\hj942\CW\meetings\conference\viewminutes.php on line 59
line 59 is the query at $result.
anyone?
"$this" is used inside a Class to refer to itself. As you're not inside a class, the php script produces an error. Use mysql_query() instead, and of course you'll need to connect to your DB first
You are using $this->db on the 5th line of your code and it's not a object context. You probably want to use $db, but also you need to initiate db connection on $db variable for it to work.
First, establish a MySQL connection:
$db = mysql_connect('db_host', 'db_user', 'db_password');
Then, use $db variable with the mysql_query() function instead of $this->db->get:
$result = mysql_query($db, 'SELECT * FROM Meetings INNER JOIN Minutes ON Minutes.meeting_id = Meetings.meeting_id WHERE Rooms.date >= "' . $from . '" AND Rooms.date <= NOW() AND Minutes.meeting_id = $id')
Or even without the $db variable (if you use only one database):
$result = mysql_query('SELECT * FROM Meetings INNER JOIN Minutes ON Minutes.meeting_id = Meetings.meeting_id WHERE Rooms.date >= "' . $from . '" AND Rooms.date <= NOW() AND Minutes.meeting_id = $id')