Date,time resets every time i use UPDATE - php

Date, time resets every time i use UPDATE,
page1
mysql_query("INSERT INTO table (time) VALUES(CURRENT_TIMESTAMP()) ") or die(mysql_error());
page2 (not connected with page1)
echo $row['time'];
and after i use
$query = mysql_query("UPDATE tablica SET views = views+1 WHERE id = '".$id."' ");
date and time resets to current date and time
and if i delete UPDATE code everything is fine,
type is timestamp,
how to stop reseting date and time?

If table field is defined as timestamp, then it'll update automatically when record is changed / updated.
Read more about timestamps and issues here:
http://dev.mysql.com/doc/refman/5.1/en/timestamp-initialization.html
MySQL CURRENT_TIMESTAMP on create and on update

Related

UPDATE row relative to CURRENT_TIMESTAMP is not giving the correct value

I am trying to update a MySQL table with an 'expiration date'. I've collected a timestamp value for all my rows as people have registered into the table but now I want to create an expiration date relative to that timestamp (not to relative to the current time). Here's my code:
$timestamp = $row['timestamp'];
$sql_update = "
UPDATE jobs
SET expiration_date = DATE_ADD('$timestamp',INTERVAL 56 DAY)";
$result_update = $mysqli->query($sql_update) or die($mysqli->error);
Understand that this is being run in a 'while' loop so it's running through each row of the table an updating them as it goes. The issue is that I ran it once and all it did was update the 'expiration_date' row to 56 days from NOW not 56 days from the timestamp's value. The timestamp is set on CURRENT_TIMESTAMP for when the a new entry is registered which I'm assuming is the problem. I've echoed out $timestamp to troubleshoot and it echoes out the correct value (not the current time) when I echo it but when it goes to actually update the expiration date it seems to be drawing from the fact that it's a CURRENT_TIMESTAMP. Is there a way to explicit query for the value of the timestamp?
I'm hoping to find a way that doesn't involved restructuring the database. I know I could have it so instead of a timestamp row, I could make it a datetime row and set it to the value of NOW() when database is being initially queried to add a row but I'd prefer to find a solution within the way the table is currently set up. Thanks!
Probably somehow the value in $timestamp is wrong.
Try adding the timestamp directly in the query using the column name. E.g. : DATE_ADD(timestamp,INTERVAL 56 DAY)
What you are currently doing, hardly makes any sense. You first get the timestamp from the database and assign it to the $timestamp variable, only to use it in the query again..
In situations like these, you can better directly use the column name to access the data in your query.
I wonder why are you running this query in loop ?
You can use only one sql statement. Update from select;
update jobs a set a.expiration_date = DATE_ADD(a.timestampFieldName,INTERVAL 56 DAY), a.timestampFieldName = a.timestampFieldName;
I supose that there is some "bug" (don't know) in MySQL because if you don't add a.timestampFieldName = a.timestampFieldName then this field will be set to current timestamp;

I want to display last login time in php

To display last login time..
i want to save login time to database in processlogin page...and fetch that for next time in login page..
i got current date and time correctly by using
$dt=date("m/d/y G:i:s<br>", time());
nd now i want to save $dt to database for that i have write below code
$qdt = "select * from lastlogin";
$rsLogin1 = $objdb->select($qdt);
if(rsLogin1 != null)
{
$qaa = "update lastlogin set last='".$dt."'";
$rsLogin12 = $objdb->select($qaa);
}
else
{
$qa = "insert into lastlogin(last) values('".$dt."')";
$rsLogin1 = $objdb->select($qa);
}
when this page is running it show me
update lastlogin set last='11/08/12 15:00:07' with statment wrong query
and when i copy and paste same query to my sql query...it give me correct result..
Can any one please help me that where i am wrong or what i have to do to solve this..
my database name is lastlogin and field is last which is varchar(200)
Thanks in Advance
If I'm understanding your question correctly, you're adding more work than is necessary. One way to store last login time would be to utilize the MySQL column type timestamp and set the default value to current_timestamp. This way you're not needing to calculate anything, and it will be populated for you. From there, just manipulate it from the database with the date() function.
you have to change the time format according to MYSQL or what ever DB
yyyy-mm-dd hh:ii:ss
Why to use VARCHAR(200) for dateand time , USe datetime for dates and time in DB
AND you did not specify the where CLAUSE in Sql, It will update all records in DB so try like that
update lastlogin set last='2012-11-08 15:00:07' WHERE ID= ???

PHP/MYSQL IP Check/Logger

Ok, ive got a minecraft server and im making a voting script for it.
I need a way to check the users ip in a mySQL.
If it doesn't exist it will put the ip in the database, and it will remove it after 24 hours in the database.
If anyone could help me do this, it would be great, thanks
There are plenty of tutorials online on how to achieve this, thus I wont give you the code. Just a few hints to get you started.
In PHP, you can get the user's ip address from the $_SERVER superglobal
$ip = $_SERVER['REMOTE_ADDR'];
To check if it exists in your table
$query = sprintf("SELECT COUNT(*) FROM yourtable WHERE `ip` = '%s'", mysql_real_escape_string($ip));
If it does not exist, store it using the INSERT command along with a timestamp.
As for removing after 24 hours, you can set up a cron job that runs through the table every hour or so and removes all entries that have expired. However, it would be easier to not remove the entries. Instead, when a user votes, just check the timestamp of his last vote. If 24 hours have passed since the last vote, just update the timestamp.
Basically, the workflow would be:
1. Get users's IP address.
2. Does this IP exist in table?
2a. If no, let user vote, and enter his ip in the table along with the current time in the timestamp column
2b. If yes, get the timestamp of his last vote. Has it been 24 hours since his last vote?
2b.a. If yes, let user vote and update timestamp column with current time.
2b.b. If no, do not let user vote / reject his vote. Leave timestamp column unchanged.
The easiest way is to do the following
$ip = $_SERVER['REMOTE_ADDR'];
// Run cleanup for given IP
$result = mysql_query("SELECT * FROM table
WHERE `ip`='$ip' AND `timestamp` > NOW() - 24*3600");
if (mysql_num_rows($result)==0)
// there is no record within the last 24h, let insert a new one
{
mysql_query("INSERT INTO table SET `ip`='$ip', `timestamp` = NOW()");
echo "Thank you for your vote!";
}
else echo "You may vote only once in 24 hours";
// run total cleanup query from time to time
if (rand(1,5)<2) mysql_query("DELETE FROM table
WHERE `timestamp` < NOW() - 24*3600");
ps: If you have different votings, each of them should have different unique ID. and the MySQL table, which had before two columns ip and timestamp, should have one more column voteid, for example. In that case the code above will change to
// voteid should be somehow set to the id of the voting.
// for example by GET request
$voteid = intval($_GET['voteid']);
$ip = $_SERVER['REMOTE_ADDR'];
// Run cleanup for given IP
$result = mysql_query("SELECT * FROM table
WHERE `ip`='$ip' AND `voteid`='$voteid` AND `timestamp` > NOW() - 24*3600");
if (mysql_num_rows($result)==0)
// there is no record within the last 24h, let insert a new one
{
mysql_query("INSERT INTO table SET `ip`='$ip',
`voteid`='$voteid', `timestamp` = NOW()");
echo "Thank you for your vote!";
}
else echo "You may vote only once in 24 hours";
// run total cleanup query from time to time
if (rand(1,5)<2) mysql_query("DELETE FROM table
WHERE `timestamp` < NOW() - 24*3600");

PHP mysql adding to a timestamp

I'm working in PHP with a MySQL db and I have a current timestamp field which is created when the field is made, I then have another field which (when a page is hit) I would like a SQL statement to insert a replica of the timestamp - only 2 days ahead. Any ideas on how I would go about doing this?
So you have a table like:
id
current TIMESTAMP DEFAULT CURRENT..
another TIMESTAMP
?
You can do something like
UPDATE MyTable SET another = ADDDATE(current, INTERVAL 2 DAY) WHERE id = :myId
MySQL Date and Time functions
How about INSERT [...] (... , ADDTIME(NOW(),'2 00:00:00' , ...)

MySQL: How many minutes ago was DB updated?

I need to keep a field in a data-base and update it with a time somehow, then later I need to check that time to see if it was over 30 minutes ago or not, and if not, how minutes left until 30?
I am going to be doing this with PHP+MySql can anyone tell me the simplest way to do this?
Thanks!!
Let's assume you want to know how long ago the last update/insert in the table occurred.
You can set up a table with a timestamp field with an on update clause
CREATE TABLE foo (
id int auto_increment,
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
primary key(id),
key(ts)
)
and then query the record with the largest value in ts
SELECT
TIMEDIFF(Now()-Interval 30 Minute, ts)
FROM
foo
ORDER BY
ts DESC
LIMIT
1
edit: This also works if you want to get all records that have been inserted/modified within e.g. the last 12 hours.
SELECT
TIMEDIFF(Now()-Interval 30 Minute, ts)
FROM
foo
WHERE
ts > Now()-Interval 12 hour
ORDER BY
ts DESC
edit2: there's also an off chance you might be interested in http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html:SHOW TABLE STATUS returns the following fields:
...
Update_time
When the data file was last updated. For some storage engines, this value is NULL. For example, InnoDB stores multiple tables in its tablespace and the data file timestamp does not apply. For MyISAM, the data file timestamp is used; however, on Windows the timestamp is not updated by updates so the value is inaccurate.
I could wrap all you insert and update MySql calls in a function something like the following:
function MySqlQuery($query, $res){
$result = mysql_query($qs, $res);
if($result === false){
mysql_query("QUERY STRING TO UPDATE FIELD IN DATABASE WITH NEW TIME", $res);
}
return $result;
}
Replace the "QUERY STRING TO UPDATE FIELD IN DATABASE WITH NEW TIME" with an actual update query and you should be good to go.
What I do is, put a Time Stamp on the latest record. Pull the latest record with a MySQL Query and then use the mysql fetch array function to get the time of that last record. This goes the same for using a database that is updated with the time only.
You would be able to manipulate that time with a function that compares the current time to the time on the record. From there you can display the time since last posting, and if it is over 30 minutes you can make it echo a message.
$currenttime = /* PHP Time Formatting you wish to use. */
$query = mysql_query("SELECT time FROM database");
$row = mysql_fetch_array($query);
echo "Last Record Posted #" . $row['time'];
$timesince = $currenttime - $row['time'];
echo "Time Since Last Post:" . $time - $row['time'];
if($timesince >= "30"){
echo "Over 30 Minutes!";
}
Let me know if you have any questions. The above code should give you an idea of how it would work, but it is a rough example.
Best of Luck!!
EDIT:::
Sorry, I misread the question, You would still need to enter the time into the database. You can still use the above code to pull the time and see if it is greater than 30 minutes or not.
For the Time Stamp check out the PHP Time Manual. You will want to pick the same time format for both the MySQL Input and the code I posted above.

Categories