how to retrieve data on compare time in php - php

My code:
$query = "INSERT IGNORE INTO `user_app` (app_id,imei, package_name, sdk_name, sdk_version, app_version)
VALUES
('".$appid."','".$imei."', '".$pkg."', '".$sdkn."', '".$sdkv."', '".$appv."')";
$mysqli -> query($query);
$id = $mysqli -> insert_id ; //get last user insert id
$idt = date('G:i:s', time());
$new = strtotime($idt);
include('requestad.php');
When a new user registered, he'll get an ad from requestad.php in json format. Insert id is save in a separate variable named $id, if a user again hit via application (as application invoke after every 30min ) then he'll get again json ad. I am trying to do some stuff like user get ad only once in whole 24hours, this is possible with insert id and insert time stamp. I am doing something like that:
if ( $new == time() ) {
include('requestad.php');
} elseif ( $new < time() ) {
echo 'nothing';
}
But problem is i didn't save exact execution time in variable and save time is necessary for comparison. Also, i have to send some blank to user if he again request for resource. Pl have a look on this and help me to produce optimal solution.
Still i didn't apply any logic yet. I can achieve this through store time which is static and compare it to time() which shows real time. Still i am looking this one

$store_time=$row['time'];//pick up the store time of user
$store_time=strtotime($row['time']);//and convert it in strtotime.if alredy did no need to do this.
$new=strtotime("-24 hours",strtotime(time()));//substract the time to -24 hours.
if($new==$store_time)
{
//your code
}
else
{
//your code
}

Related

How do I construct this snippet to store both date and time for column "publicationDate" in MySQL also adding another column "editedDate" to be added?

public function storeFormValues( $params ) {
// Store all the parameters
$this->__construct( $params );
// Parse and store the publication date
if ( isset($params['publicationDate']) ) {
$publicationDate = explode ( '-', $params['publicationDate'] );
if ( count($publicationDate) == 3 ) {
list ( $y, $m, $d ) = $publicationDate;
$this->publicationDate = mktime ( 0, 0, 0, $m, $d, $y );
}
}
}
Both columns are being stored via hidden input fields being that they cannot be set via form by user. The default value for "editedDate" is null unless the page/article is being updated as in which it will constantly change per every edit. The case for "publicationDate" is set once. The problem I'm having is the date isn't being stored even though the correct values is being set through the form (0000-00-00 00:00:00). The "publicationDate" column stores only the date with the time value being - 00:00:00 (example 2019-12-05 00:00:00) and when storing the edited date it stores all date & time values but wrong date & time being submitted to the database even though the form is submitting the correct values.
This how it's being inserted into the database
$sql = "INSERT INTO examples ( publicationDate, editedDate, title, summary, content, imageExtension ) VALUES ( FROM_UNIXTIME(:publicationDate), FROM_UNIXTIME(:editedDate), :example1, :example2, :example3 )";
In the html form the input "values" are echoed
echo date( "Y-m-d H:i:s" );
When viewing the source code in the browser the "values" are being set even the empty value for "editedDate" when it is the first time the page is created/published (publicationDate) which can be null in the database.
**I finally fixed it with a bit of trial and errors. First, in the form template only the input for "publicationDate" is sent to the browser (*hidden) with the value being echoed if the webpage/article is just being created (new) & if it's being edited only the input for "editedDate" is being sent to the browser. But then I had to change the snippet I knew was causing the values inputted in the form not being put in the database
if ( isset($params['publicationDate'])) {
$this->publicationDate = time ( );
$this->editedDate = time ("");
}
else if (isset($params['editedDate'])) {
$this->editedDate = time( );
}
}
I don't see any code related to storing the Editing timestamp, so I can't really comment on that. As for the publish date/time, look at this line:
$this->publicationDate = mktime ( 0, 0, 0, $m, $d, $y );
The php documentation here (php.net mktime) shows that the parameters to mtkime are Hour, minute, seconds, month, day, year. So, from your code, mtkime(0,0,0,$m,$d,$y) you are not attempting to store anything other than 00:00:00 for the time portion.
Have you considered altering the mysql column for pulbishingdate to have a default value of CURRENT_TIMESTAMP, and writing a trigger for before update to set the editing time to now()?
If this doesn't help you solve the problem, try to share the form structure and possibly a dump of $_POST to give more information.
From one side, we have the publicationDate, the easiest way to store this, is setting the DB to autofill it with CurrentTimeStamp() fuction, as long as you just want to store it with any further changes. It will store it just once, and by it default value (current time) if you do not specify it on the INSERT query.
On the other side, editDate, you can easily get it from the MySQL server with now() without the using of forms.
PHP
function your_edit_funcion() {
[...];
$qry = "UPDATE table SET [...], editDate = NOW()";
[...]
}

Check for new entries in a DB [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am trying to build an application that will query a db, and send data somewhere as it comes into the database.
I can get the data I want from the database using this code:
$sql="SELECT * FROM `signals` order by `time` DESC LIMIT 100";
$result = mysqli_query($DatabasePointer,$sql)
or die(mysqli_error($DatabasePointer));
$row_cnt = mysqli_num_rows($result);
if($row_cnt>0)
{
$array = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
//$a = array();
$epoch = $row['time'];
// convert UNIX timestamp to PHP DateTime
$dt = new DateTime("#$epoch");
if(
($row['symbol'] === 'USDJPYecn')
|| ($row['symbol'] === 'USDCADecn')
|| ($row['symbol'] === 'EURUSDecn')
)
{
if(
($row['timeframe'] === 'M5')
|| ($row['timeframe'] === 'M15')
)
{
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time'],
"candel" => $row['candel']
);
$array[] = $a;
}
}
} // while
echo json_encode($array, JSON_UNESCAPED_SLASHES);
}
However, I am not sure how to revise the code to check to see if the data is new, or has already been sent out to another source. I am also unsure how to revise the code to only send new data as it hits the db, not an entire array of data like I am calling now.
Can somebody please point me in the right direction?
EDIT:
$sql="SELECT * FROM `tdisignals` order by `time` DESC LIMIT 100";
$result = mysqli_query($DatabasePointer,$sql)
or die(mysqli_error($DatabasePointer));
$row_cnt = mysqli_num_rows($result);
if($row_cnt>0)
{
$array = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
//$a = array();
$epoch = $row['time'];
// convert UNIX timestamp to PHP DateTime
$dt = new DateTime("#$epoch");
if(
$row['symbol'] === 'USDJPYecn'
|| ($row['symbol'] === 'USDCADecn')
|| ($row['symbol'] === 'GBPUSDecn'))
{
if(
$row['timeframe'] === 'M5')
|| ($row['timeframe'] === 'M15'))
{
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time'],
"candel" => $row['candel'],
);
$array[] = $a;
}
}
}
// echo json_encode($array, JSON_UNESCAPED_SLASHES);
$fuegostore = json_encode($array, JSON_UNESCAPED_SLASHES);
// $sql2 = "INSERT INTO fuegosync (time, lastsync) ".
// "VALUES ('$date', '$fuegostore')";
// $result2 = mysqli_query($DatabasePointer,$sql2)
// or die(mysqli_error($DatabasePointer));
$sql3="SELECT lastsync, MAX(CAST(time AS CHAR)) FROM `fuegosync`";
$result3 = mysqli_query($DatabasePointer,$sql3)
or die(mysqli_error($DatabasePointer));
$row2 = mysqli_fetch_row($result3);
if($row2[0] === $fuegostore)
echo 'No New Signals';
else
echo 'New Signals';
///OPTION 1:
//print_r (json_encode($array[0], JSON_UNESCAPED_SLASHES));
//OPTION 2:
foreach($array as $x) {
if(strtotime($array[0]['time']) >= $row2[1]) {
echo '<br /><span>'.$x['signal'].' - '.$x['symbol'].' - '.$x['price'].'<br />';
} else {
echo 'No New Signals';
}
}
echo $row2[0];
}
This code is successfully detecting a new data hitting the database. What I am struggling with now, is revising the code to only display the newly detected data piece, not the entire array as you see it.
NEW EDIT:
I have gotten the code to display only the newest piece of data, but now I have a conundrum.
If I poll the database say every minute, and a new piece of data hits the db, the script will pick it up -- however if another new piece of data hits the db seconds after the first new piece was sent to target, the second new piece will totally get ignored because the poll would be every minute. I would basically have to poll the database every few seconds... and that sounds like a performance nightmare...
The grayed out OPTION 1 is what displays the newest data, but would skip a newer piece before a minute based poll unless the db was polled every second.
OPTION 2 works, but displays the entire array... so I am unsure how to revise the code to only display the newest pieces, not the entire thing.
Any suggestions?
Secured
One of the most secure way to do this kind of thing is :
having an incremented field on source
allowing a query on target
Step-by-step, source driven
you add some data in source, with their auto-incremented id
you query your target from source and ask for the last id know
with this id, from source, you get all new record, and query with these data an insert page on target
Alternate, target driven
you add some data in source, with their auto-incremented id
your target get his bigger id and ask source for new data
target update himself
And you can go to step one again. If you are careful on your insert (use of roll-back, break full batch on one fail), you should have a perfect target whenever the fail on the source / target link, and the bandwidth is as low as it could.
One-sided and check-less
This allow to send batch of data from source without answer nor action of target.
This don’t care if the data is lost on the way, it only send once.
having a three states field send on source
Step-by-step
you add some data in source, with their send by default on 0
you set every send ==0 on send = -1
select every -1 and send them to the target
update -1 to 1
Go back to step one.
This allow you big batch without having to put a lock write waiting the send script, and be sure you can't have some line that drop between the send one.
Timestamp
This look a lot like the previous one, but instead of a field on every row, we just use a new table to keep the last sync :
Step-by-step
you add some data in source, with their timestamp
you get the current timestamp - 1 (one second before now)
you get the last sync timestamp (or 0 if it's your first sync)
select and send lines where timestampOfPost <= timestamp-1 and timestampOfPost > timestampLastSync
update your last sync timestamp with the timestamp - 1 of point 2.
Timestamp can be tricky if you don't use the "go 1seconde back in time" and keep it in a variable, as you can lose some update :
If you send at ***754(.1)s, every line from ***754(.2)s to (.9)s will be see as send as we have done the timestamp ***754 and will start the next send at ***755.

Checking database with Recursive Function

i'm trying to do a recursive function. It's a simple id creation and checking the id inside the database. If the id is already created, then it should run the function back to create a new id and do the checking again. Below is the code.
public function session_order(){
$sr_function = new sr_function();
$session_no = (rand(0,2));
//i have set the order_id in the db as '1'//
$sql = "SELECT COUNT(order_id) as order_count
FROM src_order WHERE order_id = '".$session_no."'";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
if ($row['order_count'] == 1){
$this->session_order();
}
return $session_no;
}
how ever, when $row['order_count'] == 1, the function did not run the session_order() back to create another session no. Thank you
When you generate a successful ID, you need to pass it back up the call stack.
if ($row['order_count'] == 1){
$session_no = $this->session_order();
}
Why are you doing this with recursion? A simple iterative loop seems more reasonable. For one thing, the current implementation repeats the DB query for every ID creation. Isn't the query result supposed to be the same every time? Or are you altering the ID list in parallel?

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.

Insert multiple data as well as update in database using php?

I get Nearest 50 km location names from current location using google api, so it' works fine.
So I need to insert all these locations into my database. If some location already there in database, I need to update these location.
For example I get 10 locations in google api so 5 locations are already there in my database. I need to 5 location are update and remaining 5 locations are insert.
Here is my code:
<?php
require 'dbconnect.php';
$LocaName=$_REQUEST['locname'];
$address=$_REQUEST['address'];
$latt=$_REQUEST['Latt'];
$long=$_REQUEST['Long'];
if($latt && $long)
{
$LocaNamearray = explode("|||", $LocaName);
$addressarray = explode("|||", $address);
$lattarray=explode("|||",$latt);
$longarray=explode("|||",$long);
for($i=0;$i<count($lattarray);$i++)
{
$query1="select * from tbl_MapDetails where Latitude='".$lattarray[$i]."'and Longitude='".$longarray[$i]."'";
$result1=mysql_query($query1);
$now=mysql_num_rows($result1);
}
if($now >=1)
{
for($k=0;$k<count($lattarray);$k++)
{
$query="update tbl_MapDetails set LocationName='".$LocaNamearray[$k]."', Address='".$addressarray[$k]."',Latitude='".$lattarray[$k]."', Longitude='".$longarray[$k]."' where Latitude='".$lattarray[$k]."'and Longitude='".$longarray[$k]."'";
}
$nav="update";
}
else
{
$query ="INSERT INTO tbl_MapDetails(LocationName,Address,Latitude,Longitude) VALUES";
$strDelimiter = "";
for($j=0;$j<count($LocaNamearray);$j++)
{
$name =$LocaNamearray[$j];
$address =$addressarray[$j];
$lat = $lattarray[$j];
$long = $longarray[$j];
$query .= $strDelimiter."('$name', '$address','$lat','$long')";
$strDelimiter = ',';
}
$nav="Add";
}
$result= mysql_query($query);
if($result)
{
echo mysql_error();
$message=array("message"=>"sucessfully".$nav);
}
else
{
echo mysql_error();
$message=array("message"=>"fail".$nav);
}
}
else
{
$message=array("message"=>"require latt and long");
}
echo json_encode($message);
?>
Here insert and update working but I need to check every location in database. There is no location in database. It need to insert other location are update. how to check both these conditions matched locations are update and unmatched locations are inserted Please guide me.
Your logic is wrong in the code. What you are doing is looping through the provided data and for each set of data checking if a location with that lat/long exists and storing it in the $now variable. Once you've finished that loop, you're then checking $now and looping through the provided data again and either INSERTing or UPDATEing each set of data. So if the last set of data exists, your script will try and UPDATE each set of data. If it doesn't, your script will try to INSERT each set of data. Your code should be something like this (mixture of your code and pseudo-code):
for($i=0;$i<count($lattarray);$i++)
{
$query1="select * from tbl_MapDetails where Latitude='".$lattarray[$i]."'and Longitude='".$longarray[$i]."'";
$result1=mysql_query($query1);
$now=mysql_num_rows($result1);
if($now >=1)
{
// update table with location details
}
else
{
// insert location details into table
}
}
If this becomes a performance issue you could look at retrieving all the SELECT data first but if you're only dealing with 10 rows at a time you should be OK.
Note: depending on where your $_REQUEST data is coming from you might want to do some validation, i.e. to check you have matching sets of lat/long/name/address details.
Take a look at MySQL`s ON DUPLICATE KEY UPDATE. But you must be careful, because it is quite slow operation.
But, I think, it would be better if you just union all your SELECT requests in one using OR conditions.

Categories