How to insert result of date difference into mysql database using php? - php

<?php
function find_days($start_date, $end_date) {
$response = new stdClass();
try {
$sdate = new DateTime($start_date);
$edate = new DateTime($end_date);
$dateInterval = $edate->diff($sdate);
$response->status = true;
$response->result = $dateInterval;
return $response;
} catch (Exception $e) {
$response->status = false;
$response->result = 'Invalid Date Format';
return $response;
}
}
?>
Start Date: <input type="date" name="sdate" placeholder="start date" />
End Date: <input type="date" name="edate" placeholder="end date" />
<input type="submit" value="Find Days" />
<?php
if (isset($_POST['sdate']) && $_POST['sdate']) {
$start_date = $_POST['sdate'];
$end_date = $_POST['edate'];
//now call the function
$days_array = find_days($start_date, $end_date);
if ($days_array->status) {
echo " <input type='text' name='day'
value='.$days_array>result>days.' />";
$day = $_POST['day'];
$query = "INSERT into cart (date,edate,days)
VALUES('$start_date','$end_date','$day')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
} else {
echo $days_array->result;
}
}
My code is working perfectly. But the result is displayed only on the screen.
So I've tried to store the result by placing it in a textbox and then insert into the table in a usual way. But I got an error "Catchable fatal error: Object of class DateInterval could not be converted to string in C:\xampp\htdocs\date.php on line 45"
I don't know how to rectify this.. please help me solve this.

You have to convert it to a string using format:
<?php
$now = new DateTime();
$hour = new DateTime( "now +1hours +13minutes +22seconds" );
$diff = $now->diff( $hour );
echo $now->format('Y-m-d H:i:s');
echo "\n";
echo $hour->format('Y-m-d H:i:s');
echo "\n";
echo $diff->format('%H:%I:%S');
Output
2018-07-26 20:53:42
2018-07-26 22:07:04
01:13:22

Related

when I use "modify" on my timestamp it gives a wrong output

I want to block a someone who tried to login 4 times with a wrong password.
The problem is: When I use "modify" and change the timestamp with 15 minutes, I get -1 as output and after two minutes I get -2 as output. I tied for so long and I searched a lot on internet, but it still doesn't work.
How I want it to work:
In the database is the column: "falselog". If the username of the visiter is correct but the password is incorrect, falselog will be +1. When falselog is 4, the visiter will be banned for 15 minutes. So the visiter is able to try 4 times. After 15 minutes, the visiter can try again.
This is my object with all the code:
public function logUser($username, $password) {
// query id = 2
$sql2_1 = "SELECT
id,
password,
falselog,
lastlogin
FROM users
WHERE username ='".$username."' ";
$result2_1 = $this->con->query($sql2_1);
$fetch2_1 = mysqli_fetch_array($result2_1);
$count2_1 = $result2_1->num_rows;
$now = new DateTime('now');
$blockedSince = new DateTime($fetch2_1['lastlogin']);
$fout = $fetch2_1['falselog'];
$date_old = date ("Y-m-d H:i:s", strtotime("now"));
$block = date("i", $fetch2_1['lastlogin']) + 16;
$current = date("i", strtotime("now"));
$wait = $block - $current ;
$dbtime = date ("Y-m-d H:i:s", strtotime($date_old));
// This is the code that doesn't work
if ($fetch2_1['falselog']>=4 AND $blockedSince->modify('+15 minutes') > $now) {
$error[] = 'This account has been banned, try again about '.$wait.' minutes';
$decline = true;
$date_old = $fetch2_1['lastlogin'];
}
elseif (!preg_match("/^[A-Za-z0-9-]+$/", $username)) {
$error[] = 'De input bevat ongeldige tekens (alleen cijfers en letters toegestaan)';
}
elseif ($count2_1 === 0) {
$error[] = 'Wrong login data';
}
elseif ($fetch2_1['password']!=sha1($password)) {
$error[] = 'wrong password';
$fout = $fetch2_1['falselog']+1;
}
if ((count($error) == 0) OR ($fetch2_1['falselog']==4 AND $blockedSince->modify('+15 minutes') < $now)) {
$fout = 0;
}
$sql2_2 = "UPDATE users SET
falselog='".$fout."',
lastlogin='".$dbtime."'
WHERE username='".$username."' ";
if ($this->con->query($sql2_2) === TRUE) {
if (count($error) == 0) {
return false;
}
else {
return $error;
}
}
else {
echo "Error: " . $sql2_2 . "<br>" . $this->con->error;
return true;
}
}
You should check that here
$blockedSince = new DateTime($fetch2_1['lastlogin']);
you get the correct data for DateTime, try var_dump($blockedSince); after this line, and check that it has correct value inside;
try this
$blockedSince = mktime($fetch2_1['lastlogin']);

PHP prepare statement Notice: Only variables should be passed by reference

my first time writing prepared statement
this code is checking your late in every 3 hours then inserting the time interval into db
date_default_timezone_set('Asia/Hong_Kong');
$now = new DateTime();
if ($now->format("H:i") > "22:00") {
$deadline = DateTime::createFromFormat("H:i", "22:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
} else if ($now->format("H:i") > "19:00") {
$deadline = DateTime::createFromFormat("H:i", "19:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
} else if ($now->format("H:i") > "16:00") {
$deadline = DateTime::createFromFormat("H:i", "16:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
} else if ($now->format("H:i") > "13:00") {
$deadline = DateTime::createFromFormat("H:i", "13:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
} else if ($now->format("H:i") > "10:00") {
$deadline = DateTime::createFromFormat("H:i", "10:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
} else if ($now->format("H:i") > "07:00") {
$deadline = DateTime::createFromFormat("H:i", "07:00");
$diff = $now->diff($deadline);
echo "You are ".$diff->h." hours and ".$diff->i." minutes late";
}
$stmt = $conn->prepare("INSERT INTO time_in (e_id, login, late, date_in)
VALUES (?, ?, ?,CURRENT_TIMESTAMP)");
$stmt->bind_param("sss", $e_id, $login, $diff->format('%H:%i'));
$e_id = "id is unavailable"; // changing to $_POST in the future
$login = "1";
$status = $stmt->execute();
if(!$status) {
echo $stmt->error;
exit;
}
echo "success";
}
and im getting this
Notice: Only variables should be passed by reference
at this line $stmt->bind_param("sss", $e_id, $login, $diff->format('%H:%i'))
the code working perfectly but im getting that notice
please help
you must pass actual variables to bind_param, since $diff->format('%H:%i') is not a variable but rather the output of a function, it doesn't like that.
You will need to assign this to a variable first then pass it in. i.e
$diffFormat = $diff->format('%H:%i');
$stmt->bind_param("sss", $e_id, $login, $diffFormat);

how to update the date in database table

I want to update my databse to change all the different formats of dates into one format. I want to update different time formats into the format 2016-12-22.
I get this error:
250 Fatal error: Uncaught exception 'Exception' with message
'DateTime::__construct(): Failed to parse time string ($res1) at
position 0 ($): Unexpected character' in
/hermes/walnaweb13a/b775/moo.manhassurinder/singhaniafarm/test.php:22
Stack trace: #0
/hermes/walnaweb13a/b775/moo.manhassurinder/singhaniafarm/test.php(22):
DateTime->__construct('$res1') #1 {main} thrown in
/hermes/walnaweb13a/b775/moo.manhassurinder/singhaniafarm/test.php on
line 22
$squery = "SELECT date,id FROM `addCutting` ";
$sresult = mysqli_query($con,$squery);
while($row = mysqli_fetch_assoc($sresult))
{
"<br/>". $res1= $row['date'];
echo"<br/>". $res= $row['id'];
/* if($res1!= date('y/m/d'))
{
$result2= date_format( new DateTime($res1), 'y/m/d' );
echo $result2;
}
}
*/
/* $date1 = new DateTime($res1);
echo $date1->format('Y-m-d'); echo "<br/>"; */
$date = new DateTime('$res1');
echo $date->format('Y-m-d');
}
while($row = mysqli_fetch_assoc($sresult))
{
$date= $row['date'];
$formated_date = date('Y-m-d',strtotime($date));
echo $formated_date;
}
Try this hope it works
Referal Link on strtotime click here
I think what you what is this instead of the last 2 lines
$formated = "";
if(!emtpy($res1)){
$date = new DateTime($res1);
if(!emtpy($date)){
$formated = $date->format('Y-m-d');
}
}
echo $formated;

Trying to solve this Notice: Undefined variable

Im trying to update my table news dynamically.
And its working fine, but I want to show in my form the current values ​​that my news has, so Im using inside my value = <?php echo $read['title'] ; ?>
But with date, Im getting two errors:
Im getting this error inside my input:
Notice: Undefined variable: spanish and Undefined variable: english
I understand erros, but I wanted to ask you, if you know how I can solve this, I know if I repeat definition of my variables "spanish and english" inside my date value, it works, but it not seems correct to repeat this variables.
Do you know how I con solve this using only one definition for $english and $spanish variables??
<?php
if(isset($_POST['sendForm']))
{
$f['title'] = $_POST['title'];
$f['date'] = $_POST['date'];
if(in_array('',$f))
{
echo 'Fill all fields';
}
else
{
$english = array(); //here I have some words
$spanish = array();
$result_date = str_ireplace ($english , $spanish, $f['date']);
$date = DateTime::createFromFormat('l, j F, Y', $result_date);
$date = $date->format('Y-m-d H:i:s');
$update = $pdo->prepare("UPDATE news set title=:title, date=:date WHERE id = :id");
$update->bindValue(':title', $f['title']);
$update->bindValue(':date', $date);
$update->bindValue(':id', '20');
$update->execute();
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<label class="line">
<span>Title:</span>
<input type="text" name="title" value="<?php echo $read['title'] ; ?>" />
</label>
<label class="line">
<span>Date:</span>
<input type="text" name="date" value="
<?php
$date = new DateTime($read['date']);
$result_date = str_ireplace($spanish , $english, $date->format('l, j F, Y'));
echo $result_date;
?>" />
</label>
<input type="submit" value="Submit" name="sendForm"/>
</form>
<?php
$english = array(); //define at first because if you post the variables are unset
$spanish = array();
if(isset($_POST['sendForm']))
{
$f['title'] = $_POST['title'];
$f['date'] = $_POST['date'];
if(in_array('',$f))
{
echo 'Fill all fields';
}
else
{
$result_date = str_ireplace ($english , $spanish, $f['date']);
$date = DateTime::createFromFormat('l, j F, Y', $result_date);
$date = $date->format('Y-m-d H:i:s');
$update = $pdo->prepare("UPDATE news set title=:title, date=:date WHERE id = :id");
$update->bindValue(':title', $f['title']);
$update->bindValue(':date', $date);
$update->bindValue(':id', '20');
$update->execute();
}
}
Notices you can off through php.ini file or just use the error_reporting(0); but make sure here this will not showing any other error.
you can enable this after the site will goes to live.
may this help you!

Timezone conversion not working

To get timestamps to be in the user's time period, I have set up a timezone conversion tool with PHP for my posting system. Basically the user sets their own timezone through a dropdown, and this is stored on the database as a PHP timezone - so if I select GMT, the value in the database would be Europe/London.
The idea is then to take this from the database and plug it into a timezone conversion piece of code, but this presently isn't converting anything at all. Can anyone see the problem?
doMessage.php
$date = date("Y-m-d G:i:s");
$user_tz = $result['time'];
$schedule_date = new DateTime($date, new DateTimeZone($user_tz) );
$schedule_date->setTimeZone(new DateTimeZone('UTC'));
$date = $schedule_date->format('Y-m-d H:i:s');
core/init.php
<?php
session_start();
$db = new PDO('this is all correct');
if(isset($_SESSION['id'])) {
$i = $_SESSION['id'];
$query = $db->prepare("SELECT * FROM users WHERE id=:i");
$query->bindParam(":i",$i);
$query->execute();
$result = $query->fetch();
$ver = $result["activated"];
if($ver == 0) {
echo "Please <a href='activate.php'>verify your account.</a>";
}
}
else {
echo "Please <a href='login.php'>log in.</a>";
$guest = True;
}
To get current date and time of GMT, just this is enough:
date_default_timezone_set('GMT');
$current_date = date("Y-m-d h:i:s A T")
echo $current_date;
This outputs 2013-12-30 5:30:20 AM GMT

Categories