MySQL update DATETIME to NOW() using PHP - php

This all worked before I added the section to update "last_update".
if((time() - $last_update) > 7200){
$sql = $dbh->prepare("UPDATE item_list SET quantity=:quantity, price=:price, last_update=:now WHERE item_name=:itemname");
$sql->bindParam(':quantity', $json->volume);
$sql->bindParam(':price', $json->lowest_price);
$sql->bindParam(':itemname', $row['Item_Name']);
$sql->bindParam(':now', "NOW()"); //This doesn't work
$sql->execute();
}
When this is called I want to make last_update the date and time now. In the database it is currently a DATETIME, and when I last_update I origianly set them to NOW();
Doing this I get the error Fatal error: Cannot pass parameter 2 by reference in.... Directory
I know it expects a variable, I'm not sure how to fix it though. I tried setting
$now = "NOW()";
$sql->bindParam(':now', $now);
No prevail. Any help?

Why you need to bind, just put NOW() directly
$sql = $dbh->prepare("UPDATE item_list SET quantity=:quantity, price=:price, last_update=now() WHERE item_name=:itemname");

If your last_update column is looking for a UNIX timestamp, then do :
$now = time();
$sql->bindParam(':now', $now);
If it's after a different time format, use date(), and the relevant formatting it has to set the date and time

You can keep your bind query as it is & remove the last_update column from the query.
Since you are updating other things in the record via another query, then you can set the default value of the field last_update to CURRENT_TIMESTAMP & set it's attribute as ON UPDATE CURRENT_TIMESTAMP. That will ensure it automatically updates itself with the current time now() whenever that record is updated.
It wouldn't be the best thing to remove bind() as you rightly said to prevent SQL injection attempts.

Related

How to get hours and minutes in this code mysql php

sql_exec (($sql = "insert into posts (user_id, body, picture_url, stamp) values ($userid, '". sql_escape ($body). "','$picture_url', minute(), hour())"));
sql_exec function
function sql_exec ($sql)
{
global $my_conn;
$result = mysqli_query($my_conn, $sql);
return $result;
}
My problem is with the minute() and hour() they are not working
Are you getting a column count error? You appear to be trying to insert 5 values in to 4 columns.
If you are looking to store a timestamp against each post you might find it easier, and a lot more practical for querying, to define the stamp column as
`stamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
This will get you both date and time which will allow you sort the posts properly and the column default will mean you don't even have to supply a value for it, mysql will do it for you.
As far as my knowledge goes, PHP doesn't have any minute() nor hour() functions. What I do know, however, is that you can get both of them using PHP's date() function.
To get the current hour and minutes, you can use:
$hour = date('H');
$minute = date('i');
Please let me know if this helped you :)

Compare Date in sql table to current date

I am working on a project in which the dates in the sql table needs to be checked with current date. If the ticket goes past the current date, then the status of ticket go from Active to Expired.
I am not good at php. This is what I came up with. I wrote this function at top of the page so that each time the page loads, it checks for the date and compares. date format is yyyy-mm-dd.
What am I doing wrong. Can anyone please help me out?
$result= "SELECT date, status FROM TABLE1";
while($row = sqlsrv_fetch_array($result)){
if(strtotime($row['date']) > strtotime(date('Y-m-d'))){
$updatequery = " UPDATE TABLE1 SET $row[status] = 'Expired' ";
}}
I would advise using the PHP DateTime class it has the date diff function so you could implement like this
$today = new DateTime('today');
$expires = new DateTime($datefromdb);
$diff = $today->diff($expires);
if($diff < 1)
{
$updatequery = " UPDATE TABLE1 SET $row[status] = 'Expired' ";
}
You can use
$result= "SELECT UNIX_TIMESTAMP(date) AS unixdate, status FROM TABLE1";
and then compare
if ($row['unixdate']) > strtotime(date('Y-m-d')))
Your sql database may be on a server whose time is different from the time on the machine where you are running the code, so I would recommend doing the check and update all on the sql server side.
(Disclaimer: I use mysql, so that's how I've written my answer. I assume you can translate to whatever sql database you use)
I would recommend using MySql's date functions, which you can see here.
UPDATE TABLE1 SET status='Expired' WHERE DATEDIFF(CURDATE(), date) < 0
Below code working for me, just a single line of update query will updated less than of current date
UPDATE TABLE_NAME SET status='expired' WHERE DATEDIFF(date, CURDATE()) < 0
Thank.

mySQL Timezones Conversion

In my database, updateTime is set to TIMESTAMP and CURRENT_TIMESTAMP. But when I display the data, the time that was recorded in the database is not my local timezone but rather 3 hours later. How can I subtract those 3 hours by converting this SQL statement? Can I use CONVERT_TZ somehow inline with this statement? I don't know how to do it.
SELECT updates.updateID, updates.windowStatus, updates.onDeck, updates.updateComments, TIME_FORMAT(`updateTime`,'%r') AS showtime FROM updates ORDER BY updates.updateID DESC LIMIT 1
The Server Time Zone can be set by each client (per-connection) in order to receive the data in other TZ than UTC. In order to do that, you just have to use:
SET time_zone = timezone;
The value of timezone can be given as an offset of UTC ('+10:00', '-6:00', ...) or as a named time zone (such as 'Europe/Helsinki', 'US/Eastern', or 'MET'). Therefore, you can set your own TZ in order to receive your data in '+3:00', if I'm not mistaken.
Take into account that this offset done by the mysql server only affects NOW(), CURTIME() and values stored in and retrieved from TIMESTAMP columns (which is what you're looking for).
You could otherwise use
SELECT ##global.time_zone, ##session.time_zone;
to get the global and client-specific timezones.
There's more relevant info (and this is actually a sum-up of what I wrote) at: Time-zone support (mysql.com).
In your case, you could have something like this:
<?php
mysql_select_db($database_casualconnnect, $casualconnnect);
$set_tz_query = "SET time_zone = '+1:00'";
mysql_query($set_tz_query, $casualconnnect) or die(mysql_error());
$query_Recordset2 = "SELECT updates.updateID, updates.windowStatus,
TIME_FORMAT(`updateTime`,'%r') AS showtime, updates.onDeck, updates.updateComments
FROM updates ORDER BY updates.updateID DESC LIMIT 1";
$Recordset2 = mysql_query($query_Recordset2, $casualconnnect) or die(mysql_error());
$row_Recordset2 = mysql_fetch_assoc($Recordset2); $totalRows_Recordset2 = mysql_num_rows($Recordset2);
?>

PHP mysql query code not working

this code is not working why :(
$id = $temp['curchar'];
$data=strtotime(date('Y-m-d H:i:s'))+30; //+30 seconds to unix time
mysql_query("UPDATE `chars` SET data='$data' WHERE id='$id'");
Warning: mysql_error(): supplied argument is not a valid MySQL-Link resource in C:\Program Files\WebServ\httpd\world_1\char_info_slow.php on line 23
too many questions, you probably can start by checking
how you connect to mysql?
what is the column type for data?
is $id match any record in table?
how to verify are the matched records get updated?
if your account connect to mysql allow to do write?
ps:
$data=strtotime(date('Y-m-d H:i:s'))+30; <-- wordless ...
$data = time()+30;
pps:
at least, you should try
$sql = "UPDATE `chars` SET data='$data' WHERE id='$id'";
mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
There's no reason to generate a date in PHP just to do some date arithmetic in MySQL. You can do this far easier within mysql as is:
UPDATE chars
SET data=DATE_ADD(data, INVERVAL 30 SECOND)
WHERE id=$id
Of course, this assumes you've made data a datetime type field. If it's just an int, then why bother with all the date math, and just do data=data+30.
As well, you're generating your time value in a highly inefficient manner. You format the current date as a string, convert that string to a number, and add 30 to it. Why not just do
$data = time() + 30;
instead? time returns the current date/time as a single integer (a unix timestamp), saving you the round trip through String Land.

php: only register visit 1 per hour

How can i only save one profilevisit per hour? So if you visited at 10:10 then it wont save when you view the profile at 12:10 ?
My code right now that saves evrytime you visit:
$date = time();
$BuID= mysql_real_escape_string($v["id"]);
$uID= mysql_real_escape_string($showU["id"]);
mysql_query("INSERT INTO users_profilevisits (uID, BuID, date) VALUES ('$uID', '$BuID', '$date')") or
die(mysql_error());
update
function save(){
mysql_query("INSERT INTO users_profilevisits (uID, BuID, date) VALUES ('$uID', '$BuID', '$date')") or
die(mysql_error());
$_SESSION['saved']=time();
}
if(isset($_SESSION['saved'])){
$time = time();
if($time-$_SESSION['saved'] > 3600){
save();
}
}else{
save();
}
select the timestamp and conditionally execute the save based on timestamp. alternatively, set a session variable and conditionally execute based on that value.
if(isset($_SESSION['saved']){
$time = time();
if($time-$_SESSION['saved'] > 3600){
save($uid,$buid);
}else{
save($uid,$buid);
function save($uid,$buid){
//save stuff here
$_SESSION['saved']=time();
}
If you always set the minutes/seconds of the provided time to 0, you can create a key over date and BuID, so it wont be able to insert more than 1 row within a hour(without any checks, session-vars or subqueries).
If you need the minutes/seconds for further operations, create a new column for implementing the described method.
assuming the following table:
date INT(11)
uID INT(11)
BuID INT(11)
date2 TIMESTAMP
UNIQUE KEY `BuID` (`BuID`,`date2`)
the following query should match your needs:
INSERT INTO users_profilevisits (uID, BuID, date, date2)
VALUES ('$uID', '$BuID', '$date',FROM_UNIXTIME(UNIX_TIMESTAMP(),'%Y%m%d%H0000'))
As you have a unique key over BuID and date2(date2 will have a value of the current time with minutes and seconds set to 0), it wont be able to insert duplicate rows with the same date2+BuID
But you have to remove the or die() , because if you try to insert a duplicate key, this will result in an error.
Using this method you dont need a programming logic, the table-structure itsselve will do the work for you.
Just give the MySQL table an additional field and set it to unique. When you save the visit, save a string like "visitoruserid+year+month+day+hour" to that field. That way MySQL takes care of only allowing one per hour per user without the need for additional PHP code, sessions and time checks.
Edit:
Add. benefit: If you later choose to loose the "once per hour" condition or change it to once per day or add more conditions, you only have to change the string saved to that field without any more changes to your code.

Categories