This is really puzzling me as DATEADD should work and it isn't and wondered if anyone knew why. Here is my statement:
$r = mysqli_query($con,"SELECT ID, DATEADD(year,1,BEGINDATE) AS NEXTYEAR FROM b_crm_deal");
while($row = mysqli_fetch_array($r))
{
print "".$row['NEXTYEAR']."<br />";
}
This doesn't return anything. If I was to return the BEGINDATE it is:
2015-08-04 00:00:00
I basically want NEXTYEAR to return 2016-08-04 00:00:00. I've tried the different combinations of year, yyyy, yy and nothing is returning.
DATEADD isn't a valid function in MySQL (it's MSSQL), use date_add instead:
DATE_ADD(BEGINDATE, interval 1 year) AS NEXTYEAR
See the manual for more information.
DATEADD looks wrong to me, see https://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_adddate
so try:
$r = mysqli_query($con,"SELECT ID, ADDDATE(BEGINDATE, INTERVAL 1 YEAR) AS NEXTYEAR FROM b_crm_deal");
while($row = mysqli_fetch_array($r))
{
print "".$row['NEXTYEAR']."<br />";
}
Related
i have mySQL database table field :
description
unit
start_date
end_date
for example :
start_date : 05-07-2019
end_date : 10-08-2021
how I calculate number of years?
Try this with carbon,
use Carbon\Carbon;
$startDate = Carbon::parse('05-07-2019');
$endDate = Carbon::parse('10-08-2021');
$diff = $startDate->diffInYears($endDate);
Hope this helps :)
Try
$datetime1 = new DateTime("05-07-2019");
$datetime2 = new DateTime("10-08-2021");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
Output will be
Difference: 2 years, 1 months, 5 days
Hope this helps :)
Try to use date_diff, in your example its will return 1.
$start_date = date_create("05-07-2019");
$end_date = date_create("10-08-2021");
$diff = date_diff($start_date, $end_date);
echo $diff->y;
that's is strange, maybe is my fault. Today I launch my test and 2 of they faults (yesterday dont). This test use a control date of some bookings, and I presume the problem is that today is 31/12. I'll show you the code:
$em = $this->getEntityManager();
$query = $em->createQuery(
'SELECT b
FROM AppBundle:Booking b
WHERE b.bookingDate >= CURRENT_DATE()
AND b.bookingDate <= CURRENT_DATE()+1
ORDER ASC b.bookingDate'
)
return $booking = $query->getResult();
That way is the only way i found to check that the booking have a date at today. Is possible that this fault becouse today is 31/12? Do you have some solution?
sorry for bad english, thanks.
You can calculate the dates by Php:
$today = new DateTime('now');
$tomorrow = new DateTime('tomorrow');
$em = $this->getEntityManager();
$query = $em->createQuery(
'SELECT b
FROM AppBundle:Booking b
WHERE b.bookingDate >= :today
AND b.bookingDate < :tomorrow
ORDER BY b.bookingDate ASC'
);
return $query->setParameters(array(
'today' => $now->format('Y-m-d'),
'tomorrow' => $tomorrow->format('Y-m-d')
))->getResult();
You can avoid var $booking and return result directly.
Also you have missed ; at the end of createQuery and ORDER is ORDER BY.
Also beware with namespaces, maybe you must to use new \DateTime('now');
CURRENT_DATE()+1
returns
20161232
which seems to be pretty wrong.
A way to make it works as you want it to would be this:
DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY);
which returns
2017-01-01
I have written a function below to give me the number of jobs an employee has done in a particular 30 day period (each ID in the 'jobs column' of the table represents 1 job).
the function work fine if I only want to look back 4 week. the problem however is that I want the count to start at the beginning of each month. for example, if a person views the records on the 10th December 2013 I need the records to show all the work for December (but not the records for the preceding 30 days).
Below is my function:
$interval_1month = 'interval 4 WEEK';
function statsHowMuchWorkDoneByStaff ($staff_id, $timeInterval)
{
global $dbc;
$select = " SELECT
COUNT(job_id) AS totalnumberWork ";
$from = " FROM
staffwork
";
$where = " WHERE
staff_id = $staff_id
AND
FROM_UNIXTIME(entrytime) >= now() - $timeInterval";
$query = $select.$from. $where;
$result = mysqli_query ($dbc, $query)
or trigger_error("Query: $query\n<br />MySQL Error: " . mysqli_error($dbc));
if(mysqli_num_rows($result))
{
$row = mysqli_fetch_array ($result, MYSQLI_ASSOC);
$result = safe_output($row['totalnumbernewcontacts']) ;
return $result ;
}
else
{
return false;
}
}
Any advise on how to proceed would be greatly appreciated.
UPDATE: here is my datatable:
CREATE TABLE staffwork(
staff_id MEDIUMINT UNSIGNED NOT NULL,
job_id MEDIUMINT UNSIGNED NOT NULL,
data_table VARCHAR (65) NOT NULL,
entrytime int(11) NOT NULL,
INDEX message (staff_id)
);
If I understand correctly and you want to calculate COUNT(job_id) for a specific month by supplying any date of that month as a parameter, then you can do it this way
SELECT COUNT(job_id) total
FROM staffwork
WHERE staff_id = 1
AND entrytime >= UNIX_TIMESTAMP(LAST_DAY('2013-12-10') + INTERVAL 1 DAY - INTERVAL 1 MONTH)
AND entrytime < UNIX_TIMESTAMP(LAST_DAY('2013-12-10') + INTERVAL 1 DAY)
Note: This query is index friendly because it doesn't convert entrytime to datetime but rather convert range values (which are constants for the query) to unix time. Make sure that you have indices on entrytime and staff_id to be able to take advantage of that.
Here is SQLFiddle demo
And while you're at it consider to learn and use prepared statements instead of interpolating query strings leaving your code vulnerable for sql injections.
That being said your php function might look like this
function statsWorkDoneByStaffMember($staff_id, $month) {
global $dbc;
$sql = "
SELECT COUNT(job_id) total
FROM staffwork
WHERE staff_id = ?
AND entrytime >= UNIX_TIMESTAMP(LAST_DAY(?) + INTERVAL 1 DAY - INTERVAL 1 MONTH)
AND entrytime < UNIX_TIMESTAMP(LAST_DAY(?) + INTERVAL 1 DAY)
";
$stmt = $dbc->prepare($sql);
if (!$stmt) {
trigger_error('Prepare failed: ' . $dbc->error);
}
$stmt->bind_param('iss', $staff_id, $month, $month);
if(!$stmt->execute()) {
trigger_error('Execute failed: ' . $dbc->error);
}
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
return $result;
}
Sample usage:
$dbc = new mysqli('localhost', 'user', 'password', 'dbname');
$staff_id = 1;
//Get the number of job_id for the current month
$total = statsWorkDoneByStaffMember($staff_id, date('Y-m-d'));
//Get the number of job_id for a specific month
$total = statsWorkDoneByStaffMember($staff_id, '2013-07-01');
I have 2 buttons which execute a post operations and set a hidden variable which is used to set the MySQL query to filter the database according to date
if result = today
$query = "SELECT id,customer_name,CAST( `register_date` AS DATE ) AS dateonly,status,
DATE_FORMAT(book_date, '%m/%d/%y') FROM table WHERE book_date
BETWEEN (CURDATE() - INTERVAL 1 DAY) AND CURDATE()";
if result = week
$query = "SELECT id,customer_name,CAST( `register_date` AS DATE ) AS dateonly,status,
DATE_FORMAT(book_date, '%m/%d/%y') FROM table
WHERE book_date BETWEEN (CURDATE() - INTERVAL 7 DAY) AND CURDATE()";
I then want to use something like
$result=mysql_query($query);
while ($mytable=mysql_fetch_array($result))
{
loop and display all the information in array in a table
}
But I need the red bean equivalent of this.
The easiest way is to just paste the $query inside the sql function:
$results=R::getAll($query);
foreach($results as $row){
echo $row['id'];
}
The next way is to manually build the query.... which may just make it look sloppier in my opinion:
$results=R::$f->begin()->select('id, customer_name, CAST( register_date AS DATE ) AS dateonly,status, DATE_FORMAT(book_date, '%m/%d/%y')')->from('table')->where('book_date BETWEEN (CURDATE() - INTERVAL 1 DAY) AND CURDATE())->get();
The final way is to grab results via redbean and handle them manually:
$results=R::find('table','book_date BETWEEN (CURDATE() - INTERVAL 7 DAY) AND CURDATE()');
Then loop through the results, configuring data along the way in php.
I always use this when I have to access a lot of data from mysql:
while ($row = mysqli_fetch_array($query)) { #converts query into array
$array[] = $row;
}
$array will be a multidimensional array. $array[x][column_name] will get you your data, x being the row which you want to access it from. Hope this helped.
I had a mysql table called events with the fields: id, date, and name.
The date field has the format yyyy-mm-dd hh::mm:ss edit: meaning it is in datetime format
I want to group the events by day, and I wasn't sure how to approach this- is there a way to select only the month and day from the field? or should i use PHP after I select all the "events"
my end goal is to have something like this:
March 10th:
event1,
event2
March 11th:
event4,
event5
I found MySQL select using datetime, group by date only but I'm not sure how to implement it:
SELECT DATE_FORMAT(date, '%H%i'), DATE_FORMAT(date, '%M %D'), name FROM events ORDER BY date
Thanks!
EDIT:
ended up using this:
$sql = "select team1, team2, DATE_FORMAT(date,'%Y-%m-%d') as created_day FROM games WHERE attack = '1' GROUP BY created_day";
$result = mysql_query($sql);
$curDate = "";
while (list($team1, $team2, $date) = mysql_fetch_row($result))
{
if ($date != $curDate)
{
echo "$date --------\n";
$curDate = $date;
}
echo "game data: $team1 $team2";
}
If you use group by you will not get one row out of it. So the way you want is not possible through Group By AFAIK.
$query = "SELECT distinct(DATE_FORMAT(date, '%M %D')) as d FROM yourtable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
echo $row['d']
$sql = "SELECT * FROM yourtable WHERE DATE_FORMAT(date, '%M %D')='$row[d]'";
$rs = mysql_query($query);
while($r = mysql_fetch_assoc($rs)) {
echo "event";
}
}
You should indeed use php to get this done. But since most of current system sepate logic from display, I'd use only one pass and not (NUMBER OF DAYS + 1) SELECTs, and prepare an array that I can reuse later for my display.
$query = "SELECT DATE_FORMAT(date, '%M %D') as d, name FROM yourtable ORDER BY date";
$foo=array();
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
//some logic to test if it's safe to add the name
$foo[$row['d']][]=$row['name'];
}
And then when i'd need it (through a template or your "view")
foreach($foo as $date => $events) {
echo $date . ":\n\t";
echo implode(",\n\t", $events);
echo "\n";
}
so it fits the format you set to yourself.
Hope that helped
I think from that question/answer, you can get something like this instead
March 10th, event1
March 10th, event2
March 11th, event4
March 11th, event5
It does not really 'group' dates as your wish but I think you can use php to continue from this result.
I agree with Kharaone, separate logic from display. That being said, I think that something similar to this query might be what you are looking for:
SELECT A FROM
(
SELECT DATE_FORMAT(date,'%M %D:') AS A, DATE(date) AS B, 1 AS C FROM games GROUP BY DATE(date)
UNION ALL
SELECT name AS A, DATE(date) AS B, 2 AS C FROM games
) X
ORDER BY B, C ASC;