Allowing users to bump an input they submitted every hour? - php

I want people to be able to "bump" what they've wrote in my database but at the same time only allow the input to be in the table ONCE at a time.
For Example:
Jim's code is 5555. Jim enters his code and it shoots to the very bottom of the table. After 34 minutes he tries to enter his code in again (Because various other people have inputted their code between now and then) but gets a display error letting him know he has 26 minutes to wait still.
Joe inputs his code and waits an hour and five minutes and is able to push his code back to the bottom again.
Basically, I'm displaying data from the bottom up in my table.
Is there any way to easily do this?
function some_more_custom_content() {
$output="<BR>";
ob_start();
if ($_REQUEST['code'] != "") {
$code = $_REQUEST['code'];
$query="INSERT INTO `fc` (`code`,`datetime`) values ('" . mysql_real_escape_string($code) . "', now())";
$result=mysql_query($query);
$entry['datetime'] = strtotime($entry['datetime']);
while ($fetch_array = mysql_fetch_array($result)) {
$seconds = time() - strtotime($fetch_array["datetime"]);
if ((time() - $entry['datetime']) < 60*60) {
echo ("The code " . htmlentities($code) ." was updated less than an hour ago.");
} else {
echo ("Inserted " . htmlentities($code) ." into the top.");
}
}
?>
I get a syntax error. Any idea where it is?
UPDATE: Getting error of:
Parse error: syntax error, unexpected $end

you should create a table with a unique index on the code field and then use a query like:
INSERT INTO CODES (code)
VALUES (555)
ON DUPLICATE KEY UPDATE lastUpdated =
case when NOW() - INTERVAL 5 MINUTE > lastUpdated
then NOW()
else lastUpdated end
this will update the lastUpdated field only in cases when it's older than 5 minutes

Not that hard:
Use a timestamp for the last "bump time".
When a code is entered, check if it already exists in the database.
If it doesn't, insert it and set the bump timestamp to now().
If it does exist, check if the timestamp was within the hour.
If it was, display error.
If it wasn't, reset it to now().
Sort your display data by bump timestamp.
EDIT:
$entry = /* get entry from database, assuming the case where it already exists */;
// depending on the format of timestamp you get from the database,
// you may have to convert it to a UNIX timestamp:
$entry['timestamp'] = strtotime($entry['timestamp']);
if ((time() - $entry['timestamp']) < 60*60) { // 60*60 is one hour in seconds
// display error
} else {
// reset bump
}

Related

PHP : comparing fetched date with today

i'm saving time for first login ,now when user logs in i enter time using NOW() function, that saves time in this format (data type is DATETIME.
2015-12-24 15:47:30
Now logic is like every login is first login so i've to check if there already exists an entry for today to check that i fetch time explode it and get time like this
$logintime= mysqli_query($connection,"SELECT loggedin from employees");
$loggedin_time= mysqli_fetch_assoc($logintime);
$Date = $loggedin_time['loggedin'];
$loggedin_time_converted= explode(" ",$yourDate) ;
$ConvertedDate = $loggedin_time_converted[0];
last line returns 2015-12-24 now i've date
$today= time();
$DateToday= date("Y-m-d",$today);
$DateToday also returns me same format and same date now i need your help me to compare these dates , if they are equel i dont uopdate database if they are not i will , Pleas help me how do i compare these values
You can do the test in MySQL
$result = mysqli_query($connection, "SELECT DATE(loggedin) = CURDATE() AS logged_in_today FROM employees");
$row = mysqli_fetch_assoc($result);
if (!$row['logged_in_today']) {
// code to update database
}
Wow, you've done all the hard stuff to get the problem to the point of being a simple comparison of 2 strings. This is all you need to do to get over the finish line ...
if ($ConvertedDate !== $DateToday) {
// update the database
}
You can use Php Built In function "Date Difference."
Code Seems Like As Follow:-
$today= time();
$DateToday= date("Y-m-d",$today);
$diff = date_diff($today,$DateToday);
echo "$diff days";
This will return values something like +12 days or something else.

How to check for time/date conflicts (PHP/MySQL)

We currently have a system, where we have a function that checks for date/time conflicts, that we manually populate all possible date/time conflicts as parameters to.
ie:
//session conflicts checker
function chkConflicts($sessions) {
if (!is_array($sessions)) {
$arrsessions = explode(',', $sessions);
} else {
$arrsessions = $sessions;
}
$conflictcount = 0;
foreach ($arrsessions as $thissession) {
if (($_POST[trim($thissession)] != '' && $_POST[trim($thissession)] != 0) || $_POST[trim($thissession) . '_faculty'] != '' && $_POST[trim($thissession) . '_faculty'] != 0) {
$conflictcount++;
}
}
if ($conflictcount > 1) {
return false;
} else {
return true;
}
}
used like so:
if (!chkConflicts('hours_5_p02_800, hours_5_p03_800, hours_5_p07_800, hours_5_p04_800')) {
$errmsg .= 'There is a conflict at 8:00am in the selections. ';
}
its very tedious, and time consuming to find these as well as manually populate the functions/params..
I need a new approach! I'm hoping to just get a list of the conflicts back and highlight the (table) row on the page with a message about you have conflicts in the highlighted areas (less specific then giving an exact time..etc, and still gets the job done for the user)
All the user interaction is done by checkboxes, that have a name that reflects the column in the table:
ie:
hours_5_p02_800, hours_5_p03_800, hours_5_p07_800,
hours_5_p04_800,hours_9_reg_session_300_845
(same names used in the chkConflicts function above)
I have (among others) two columns: sessiondate varchar(255) & presentationtime varchar(255) respectfully.
With the session date data looking like: 9/9/2015
And the presentation time data looking like: 8:45 AM - 9:05 AM (not sure if this matters, but including it for the sake of full disclosure)
I dont have ALOT of control over the database, but I could probably get the times split into two columns (start/end) if that would be best?
before ANY chkConflict function is called.. the 'selections' of the user are recorded/saved to the table.. AND THEN the conflict check is called.
//record hours for each day
function recordHours() {
$arrflds = explode(',', $_POST['fieldlist']);
$sql = "UPDATE {$this->eventcode}_cme SET";
foreach($arrflds as $key) {
$sql .= " " . addslashes(trim($key)) . " = '" . addslashes($_POST[trim($key)]) . "',";
}
$sql .= " lastupdated = '" . date('Y-m-d H:i:s') . "' WHERE id = '" . $_SESSION[$this->eventcode . '_id'] . "'";
$this->debugout .= ($this->debug) ? 'Record hours: ' . $sql . '<br>' . $this->crlf : '';
$result = mysql_query($sql) or exit('Error recording hours: ' . mysql_error());
}
*I'm updating things to PDO after I get the conflict stuff figured out. (thanks)
I dont mind this, because the chkConflict function (even though the choices have been saved) does NOT let the user move ahead until the error(s) message is taken care of (hence updating the table again when the conflicts are resolved)..
I'm thinking I'll need to no longer use the the chkConflict method and alter the recordHours function to not only update the table.. but because it has the 'fieldlist' array that was posted.. that I'll need to do the conflict checking there as well... or possibly call another function from withing recordHours and pass along the same fieldlist...
The column data is not really used for saving or (current) conflict checking of any sort... the column NAME is.
My problem is I'm not sure how to go do the date/time conflict check?
re-cap: fieldlist and column names are named like:
ie: hours_5_p02_800, hours_5_p03_800, hours_5_p07_800,hours_5_p04_800,hours_9_reg_session_300_845
(and is a 24 hour format for the time)
ex: hours_9_reg_session_300_845
9 = date
reg = event code
300 = session code
845 = session time(24-hour format)
Upon thinking more, its more like I need to do some sort of string parsing in PHP (on the fieldlist names) and do conversion/checking on that?
I need to take the string, break it down into its parts and do some sort of (concatenate/string building) comparison on it?
basically I get list of the fields being submitted that are formatted as above and match the table column names...
how can I pass this same fieldlist over to a new function (or whatever) to get any conflicts back?
Since you seem have the chance to change things a little I would suggest you to create the 2 fields but as timestamps field type. One for the start and one for the end.
You can look at timestamps fields as a date/time like 2015-10-17 08:45:00 or, using UNIX_TIMESTAMP('2015-10-17 08:45:00'), as an integer like 1445064300 which is exactly the same date/time info.
In both cases you can do things like
SELECT :yourdatetime BETWEEN date_time_start AND date_time_end;
or
SELECT :yourunixlikedatetime
NOT BETWEEN UNIX_TIMESTAMP(date_time_start) AND UNIX_TIMESTAMP(date_time_end);
for instance...

post throttling using php mysql and an epoch timestamp not functioning

I'm trying to throttle posts by users via php, mysql, and an epoch timestamp in my database stored in the row timestamp (ex: 1406059107).
My script executes as intended the first time and throttles the user for 60 seconds, but after that I can literally flood the server with posts since the throttling stops functioning.
I tried using ASC instead of DESC without success.
$sql = "SELECT timestamp FROM phpbb_schedule WHERE username = " . (int) $user->data['user_id'] . " ORDER BY timestamp DESC";
$result = $db->sql_query_limit($sql, 1);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if (time() - $row['timestamp'] < 60)
{
header( 'Location: someurl.php' );
die ('Your can only input one request every 60 seconds.');
}
else
{
echo 'success some other code goes here that inputs the data into the db and redirects this to another page';
}
Note: The issue has been resolved I didn't use ORDER by timestamp and a syntax error had occurred (see comments).

php !isset and empty not working

Pulling my hair out on this, it has to be obvious, but I can't see it today.
I built a small monitoring tool for an app we have. I want to do a check in the DB to make sure the backend scripts are working and the data isn't stale by more than 15 min. When no records are returned in a certain timeframe it should pop up a message saying to check the script. If they are not returned it should be an empty dataset and I should get a message on it.
Problem is, I can't get empty() or !isset to work. Actually regardless of whether I use !empty(), empty(), isset() or !isset(), my $tripped variable never gets tripped. I have this working for other alerts, but this one seems to be stubborn and I don't see what I'm missing.
PS I know mysql_ is out of date.
The relevant piece of code:
$ldap_check = mysql_query("SELECT
*
FROM ldap_conns
WHERE DATETIME > DATE_SUB(NOW(), INTERVAL 15 MINUTE)
order by DATETIME DESC
LIMIT 1");
while($row = mysql_fetch_array($ldap_check))
{
if (empty($row['DATETIME']))
{
echo '<b><font color=blue>Stale Data: </font> <font color=red>LDAP data is old, check script!</font><br>' . $row['DATETIME'];
$tripped='Yes';
}
}
if ($tripped!='Yes')
{
echo '<b><font color=blue>Stale Data: ' . $row['DATETIME'] . '</font></b> <font color=green> No Problems Found<br></font>';
}
You are doing it wrong... Want just check if there exists any old items? Use count! There is no reason for selectin g ALL fields from ALL records from the table. This is wrong using of database! Use count, and make index on DATETIME field!
$result = mysql_query("SELECT
count(*) old_items
FROM
ldap_conns
WHERE
DATETIME < DATE_SUB(NOW(), INTERVAL 15 MINUTE)");
$row = mysql_fetch_row($result);
if ($row['old_items']) {
echo 'There is '.$row['old_items'].' old items!';
}
You have this condition in your query:
WHERE DATETIME > DATE_SUB(NOW(), INTERVAL 15 MINUTE)
So I don't see how $row['DATETIME'] could ever be empty for any of the rows fetched (although you are actually only fetching one row...).

comparing timestamps

HI, My php is very rusty and I can't quite remember how to do this.
I have a script that i only want to call every 15 minutes. I've created a table called last_updated. What I want to do is have some code at the top of my script that queries this last_updated table and if now() minus the last updated is greater than 15 minutes then run the script and also update last_updated to now...if it isn't don't run the script. Does this make sense?
Now I know when I'm updating last_updated I need to use now() To put a new timestamp in but I;m not sure how to do the comparing of now with the db value to see if it's greater then 15 mins.
Any ideas
<?php
$pdo = new PDO('mysql:host=your_host;dbname=your_database', $user, $password, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
// query the database. change
$stmt = $pdo->query('SELECT UNIX_TIMESTAMP(last_updated_date) FROM last_updated ORDER BY last_updated_date DESC LIMIT 1');
$lastUpdatedTimestamp = $stmt->fetch(PDO::FETCH_COLUMN);
if ((time() - $lastUpdatedTimestamp) > (60 * 15)) {
touch($file);
// do stuff
}
time() gives you the current time in seconds. You should probably unroll 60 * 15 to 900, I just provided it with both numbers to illustrate what was going on.
Also, a file might be better for this than a database table. Have a look at the touch()
function. It changes the modification time of a file, or creates an empty file with the current time as the mod time if it doesn't exist. You can check the file mod time with filemtime()
<?php
$lastUpdated = null;
$file = '/path/to/writable/file/with/nothing/in/it';
if (file_exists($file)) {
$lastUpdated = filemtime($lastUpdated);
}
if (!$lastUpdated || (time() - $lastUpdated) > 900) {
touch($file);
// do stuff
}
You seem to use MySQL as the DBMS. In that case and if you want you can let MySQL do most of the work:
SELECT
pit < Now()-Interval 15 Minute as mustUpdate
FROM
last_updated
WHERE
siteId=?
pit is your DateTime field and siteId is some condition you may have if you store more than one record in the table (which sounds like a good idea to me).
The result (if there is such a record with siteId=?) contains a field mustUpdate which either contains 0 or 1, 1 indicating that the value of pit is more than 15 minutes in the past.

Categories