updating a datetime sql value by exactly a year - php

im trying to get a datetime variable (example: 2019-02-10 03:13:33) to update exactly a year. i read that datetime is written as a string so i tried to subtract by itself and add +365.
the code works if i take out all "expirationdate" including the bind value. also for some reason, i have to keep my UPDATEs encased in single quotations because theres no changes in my database if they are inside double quotes.
$stmt = $db->prepare('UPDATE usr_customer_profile SET packageid = 3, expirationdate = .'$oneyear'. WHERE usrcustomerid = :usrcustomerid');
$stmt->bindValue(':expirationdate', $_SESSION['expirationdate'], PDO::PARAM_STR);
$stmt->bindValue(':usrcustomerid', $_SESSION['usrcustomerid'], PDO::PARAM_INT);
$oneyear = (':expirationdate' - ':expirationdate') + 365;
$stmt->execute();

You can do this in PHP or SQL. In PHP you can use strtotime or (preferably) the DateTime class to add one year to the value in $_SESSION['expirationdate']:
// using strtotime
$expirationdate = date('Y-m-d H:i:s', strtotime($_SESSION['expirationdate'] . ' + 1 year'));
// using DateTime
$expiration = new DateTime($_SESSION['expiration_date']);
$expiration->add(new DateInterval('P1Y'));
$expirationdate = $expiration->format('Y-m-d H:i:s');
// do the query
$stmt = $db->prepare('UPDATE usr_customer_profile
SET packageid = 3,
expirationdate = :expirationdate
WHERE usrcustomerid = :usrcustomerid');
$stmt->bindValue(':expirationdate', $expirationdate, PDO::PARAM_STR);
$stmt->bindValue(':usrcustomerid', $_SESSION['usrcustomerid'], PDO::PARAM_INT);
$oneyear = (':expirationdate' - ':expirationdate') + 365;
$stmt->execute();
In SQL use + INTERVAL 1 YEAR to add 1 year to the expiration date:
$stmt = $db->prepare('UPDATE usr_customer_profile
SET packageid = 3,
expirationdate = :expirationdate + INTERVAL 1 YEAR
WHERE usrcustomerid = :usrcustomerid');
$stmt->bindValue(':expirationdate', $_SESSION['expirationdate'], PDO::PARAM_STR);
$stmt->bindValue(':usrcustomerid', $_SESSION['usrcustomerid'], PDO::PARAM_INT);
$oneyear = (':expirationdate' - ':expirationdate') + 365;
$stmt->execute();

Related

Issue displaying correct week from MySQL database

I have a expenses script that displays the current week by week number based on week number in the database (w10) and can select other weeks by using ?selectWeek=w46
We have been using this script for a year now and does not show the information for this week (w10) because there are 2 entries in the database for w10 and it's getting confused which one to display.
Database Structure
ID - Base_Charge - Week - Year - Created_ At
1 - 20000 - w10 - 2021 - 2021-03-08
53 - 454333 - w10 - 2022 - 2022-03-07
Code:
<?php
include '../main.php';
check_loggedin($pdo);
// output message (errors, etc)
$msg = '';
$stmt = $pdo->prepare('SELECT * FROM expense_base_charge');
$stmt->execute();
$weekList = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(isset($_GET['selectWeek'])){
$week = $_GET['selectWeek'];
}else{
$ddate = date('y-m-d');
$date = new DateTime($ddate);
$week = 'w'.$date->format("W");
}
$stmt = $pdo->prepare('SELECT * FROM expense_base_charge where week = ?');
$stmt->execute([$week]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $pdo->prepare('SELECT * FROM expense where week = ?');
$stmt->execute([$base_charge['id']]);
$expense = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
Any idea how to make it view the correct week please?
When you want select only current year records you can improve your where statement in next way:
$week = 'w10';
$stmt = $pdo->prepare(
'SELECT * FROM expense_base_charge WHERE week = ? AND year = YEAR(NOW())'
);
$stmt->execute([$week]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);
PHP MySQL Feddle
Another way, you can calculate default week/year values in PHP
(in next example I also changed week column format to int)
//set current week/year values when they not provided by GET
$week = $_GET['selectWeek'] ?? date('W');
$year = $_GET['selectYear'] ?? date('Y');
//debug only print
printf('YEAR: %d, WEEK: %d ' . PHP_EOL, $year, $week);
//select data fom MySQL using week & year
$stmt = $pdo->prepare(
'SELECT * FROM expense_base_charge WHERE week = ? AND year = ?'
);
$stmt->execute([$week, $year]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);
Test online
The problem is that you are storing the value for week and year in a denormalized form. The week number should not be stored with prefix w. Ideally, you would store both of them in a single column. Then you could use YEARWEEK() function in SQL.
This is of course assuming that you are using ISO 8601 week numbering. If you are not following this scheme then fetching the correct value will be very difficult.
If you don't want to change the table schema now, you can still get the same value using PHP. Use 'o' for year number and 'W' for week number.
$week = $_GET['selectWeek'] ?? 'w'.(new DateTime())->format("W");
$year = $_GET['selectYear'] ?? (new DateTime())->format("o");
$stmt = $pdo->prepare('SELECT * FROM expense_base_charge where week = ? and year = ?');
$stmt->execute([$week, $year]);
$base_charge = $stmt->fetch(PDO::FETCH_ASSOC);

Update Mysql row where date equal to todays date

I am trying to update a row in my table where the date in a column is equal to today's date.
I have today's date in a variable $currentDate and when I echo this out it is displayed on the screen in the following format
2020-05-08
Which looks same format as the Db table, but I still get the error invalid datetime format.
Below is the code I'm using. Any help please
$currentDate = date("Y-m-d");
$currentTemp = 33;
echo $currentDate;
$sql = "UPDATE weather_station SET currentTemp = $currentTemp WHERE date = $currentDate";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$sql = "UPDATE weather_station SET currentTemp = :temp WHERE date = :currenDate";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":temp", $currentTemp);
$stmt->bindParam(":currenDate", $currentDate);
$stmt->execute();
This works now

Between clause is returning 0 records

I have 3 records in the database matching the criteria but when I run query with between clause it is getting 0 records.
$current_date = date('m-d-Y', strtotime('monday this week'));
$upcoming_date = date('m-d-Y', strtotime('monday next week'));
$sql = mysqli_query($connection, "SELECT * FROM result WHERE test_date BETWEEN $current_date AND $upcoming_date AND login = '".$_SESSION['uid'] ."'");
$total_check = mysqli_num_rows($sql);
Here is my database
result_id`, `login`, `test_id`, `test_date`,
(1, '2', 6, '08-03-2016',
(2, '2', 5, '08-03-2016',
(3, '2', 3, '08-03-2016',
Please let me know where and what I am doing wrong as I am getting 0 results and $_SESSION['uid'] is 2
You should use ' for $current_date AND $upcoming_date
"SELECT * FROM result WHERE test_date BETWEEN '$current_date' AND '$upcoming_date' AND login = '".$_SESSION['uid'] ."'"
Use prepare statement like below to avoid SQL Injection
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
You are storing your dates incorrectly if you want to use them in range searches like BETWEEN. You must store them in DATE columns. Storing them in VARCHAR() columns is a bad idea.
You could use something like this, using STR_TO_DATE() to work around your misdesigned table.
$current_date = date('Y-m-d', strtotime('monday this week'));
$upcoming_date = date('Y-m-d', strtotime('monday next week'));
$sql = mysqli_query($connection, "SELECT * FROM result WHERE STR_TO_DATE(test_date,'%d-%m-%Y') BETWEEN '$current_date' AND '$upcoming_date' AND login = '".$_SESSION['uid'] ."'");
To ask MySQL to compare the strings 01-01-2016 and 12-31-2015, and determine that the latter comes before the former is unreasonable. String comparison is lexical. However, 2015-12-31 obviously comes before 2016-01-01.
This is a little tricky to get right, because the text string 08-08-2016 does come before 08-15-2016, by accident. But at the end of year, things collapse.

MySQL WHERE 'all' when no value supplied

I am writing a tool to search through different records in my database, where you have to specify the year. However, if no year value is entered, or is equal to zero, I want to be able to select all records.
$stmt = $mysqli->prepare("SELECT * FROM performances WHERE year = ?");
$stmt->bind_param("i", $year);
I have tried to do if statements, but they fail because then there are more parameters in bind_param than spaces in the query, m.sh:
$stmt = $mysqli->prepare("SELECT *
FROM performances
. (($year != 0) ? " WHERE year = ? " : " ")
. "");
$stmt->bind_param("i", $year);
Thanks
You can achieve this in different ways, like:
$stmt = $mysqli->prepare("SELECT * FROM performances WHERE year = :year or 0 = :year");
$stmt->bind_param("year", $year);
ShyForNow has a pretty good answer. I'd also recommend to validate inputs going into SQL:
$year = sprintf("%d", $year); -- or even throw exception if $year is not numeric
if ($year > 0) -- or could also write if ($year >= $minAcceptableYear and $year <= $maxAcceptableYear)
{
$stmt = $mysqli->prepare("SELECT * FROM performances WHERE year = ?");
$stmt->bind_param("i", $year);
}
else
{
$stmt = $mysqli->prepare("SELECT * FROM performances");
}

Update end time and duration in same time, using TIMESTAMPDIFF PHP MYSQL

I want to update 'duration' and 'end_time' field in same query/action. 'end_time' field filled current time, 'duration' field filled from different minute between 'start' and 'end_time' field. when i execute this update, the result in 'duration' field is 0. How to get end_time and duration in same time.
this is the php code :
<?php
include("koneksi.php");
$id = $_GET['id'];
$start = gmdate("Y-m-d H:i:s", time()+60*60*7);
$end_time = gmdate("Y-m-d H:i:s", time()+60*60*7);
$duration = $_POST['duration'];
$query = "update billing set end_time='$end_time', duration = TIMESTAMPDIFF(MINUTE, '$start', '$end_time') where id='$id'";
$result = mysql_query($query);
if ($result){
echo '<script language="javascript">window.location = "../?p=los"</script>';
} ?>
Duration is being set to 0 because $start and $end_time are the same.
Consider your code:
$start = gmdate("Y-m-d H:i:s", time()+60*60*7);
$end_time = gmdate("Y-m-d H:i:s", time()+60*60*7);
$query = "... TIMESTAMPDIFF(MINUTE, '$start', '$end_time') ...";
Because $start == $end_time, the difference will always be 0.
You probably want to use the value of start_time already stored in the database, not the recently created php variable $start. Perhaps something like this:
$query = "
update billing set
end_time='$end_time',
duration = TIMESTAMPDIFF(MINUTE, start_time, '$end_time')
where id='$id'
";
where start_time is a column in the database.
Note: mysql_* functions are deprecated, and you are susceptible to SQL injection. Consider using mysqli or pdo and utilize prepared statements.
thank you for your answer, and this is my fix code
$query = "update billing set , end_time='$end_time',
duration = TIMESTAMPDIFF(MINUTE, start, '$end_time'),
cost = TIMESTAMPDIFF(MINUTE, start, '$end_time') * (SELECT basiccost from costed where id ='1')
where id='$id'";

Categories