How to fix reading from till to date and time mysql? - php

On my testpage i have 2 bootstrap datetime pickers.
When the user selects a start date/time and a end date/time and push the button the screen will be filled by data from sql database.
But i have trouble reading from the right time, date is no problem.
The code what i have is this.:
$date=$_POST['q'];
$date=explode(' ',$date);
echo "Date".': '.$date[0]."<br/>";
echo "Time".': '.$date[1]."<br/>";
$date1=$_POST['q1'];
$date1=explode(' ',$date1);
echo "Date".': '.$date1[0]."<br/>";
echo "Time".': '.$date1[1]."<br/>";
$a1 = $_POST['a1'];
$q = $date[0];
$q1 = $date1[0];
$q2 = $date[1];
$q3 = $date1[1];
$query = mysqli_query($conn,"SELECT *
FROM `metingen`
WHERE (Datum >= '$q' AND Datum <= '$q1')
and (Tijd >= '$q2' AND Tijd <= '$q3')
ORDER BY Id DESC");
Its not pritty but witout the tijd(time) its works great, with tijd(time) i miss data.
The date and time i split, as you can see , because the database what i want to use is not made by me, so the date is a seperated column and also time a seperated and both are also text.
if i echo the explode date/time a see.:
Date: 15-02-2019
Time: 01:00:32
Date: 16-02-2019
Time: 22:55:33
But the data what i get is from 15-2-2019 00:30:56 and till 15-2-2019 22:11:08
I don't see all the dates i miss dates from the 16 and i get dates before my start time.
I think i have something wrong in my sql rule but , i don't know what.
can somebody help me please.
This is my create and insert code of my table (i shorted it in a bit).:
CREATE TABLE `metingen` (
`Id` int(11) NOT NULL,
`Datum` varchar(255) DEFAULT NULL,
`Tijd` varchar(255) DEFAULT NULL,
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Gegevens worden geëxporteerd voor tabel `metingen`
--
INSERT INTO `metingen` (`Id`, `Datum`, `Tijd`) VALUES
(1, '17-1-2019', '10:31:39'),
(4, '18-1-2019', '10:30:01'),
(40, '28-1-2019', '23:59:42'),
(41, '28-1-2019', '00:50:12'),
(42, '29-1-2019', '02:00:42'),
(49, '29-1-2019', '06:22:53'),
(56, '5-2-2019', '19:35:02'),
(236, '13-2-2019', '13:58:43')
ALTER TABLE `metingen`
ADD KEY `Id` (`Id`);
ALTER TABLE `metingen`
MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=319;

You should not store date and time as separate fields in your database. You should just combine them into one datetime field in your database. You should then insert and compare such datetime values in one of the supported literal formats, such as YYYY-MM-DD H:m:s
Now back to your original situation. The problem is that you require the time condition also when the table's date is strictly between the two extreme dates (not equal to either of them). In that case there should be no constraint on the time part: all times would be OK on such days.
So here is how the SQL would look:
SELECT *
FROM metingen
WHERE ( Datum > '$q' OR ( Datum = '$q' AND Tijd >= '$q2' ) )
AND ( Datum < '$q1' OR ( Datum = '$q1' AND Tijd <= '$q3' ) )
ORDER BY Id DESC
But again, this is not the best practice.
If you have stored your dates as varchar (not as date), using the D-M-YYYY format, while your input is DD-MM-YYYY, then it becomes even more complex (and slow):
SELECT *
FROM metingen
WHERE ( STR_TO_DATE(Datum, '%d-%m-%Y') > STR_TO_DATE('$q', '%d-%m-%Y')
OR ( STR_TO_DATE(Datum, '%d-%m-%Y') = STR_TO_DATE('$q', '%d-%m-%Y')
AND Tijd >= '$q2' ) )
AND ( STR_TO_DATE(Datum, '%d-%m-%Y') < STR_TO_DATE('$q1', '%d-%m-%Y')
OR ( STR_TO_DATE(Datum, '%d-%m-%Y') = STR_TO_DATE('$q1', '%d-%m-%Y')
AND Tijd <= '$q3' ) )
ORDER BY Id DESC
Another issue is that you inject strings that are posted to the page, and so they are user-driven. This represents a SQL Injection vulnerabilty. Instead you should use prepared statements and pass the datetime strings as parameters.

Related

How to insert current date in database mysql

hello i am using insert query with a different pattern so i just want to
insert the current date in database but i can't find a place to put $date in insert query
$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));
$sql="INSERT INTO `delivery`(product_id,pr_name,pr_price,pr_size,user_id)
SELECT `product_id`,`pr_name`,`pr_price`,`pr_size`, `userid`
FROM `shopping_cart` WHERE `userid` = $uid";
You should not pass date or datetime from PHP if you want the date/datetime at the time of yours query's execution, instead you can use built-in MySQL functions to do so
To insert current date & time use NOW()
$sql="INSERT INTO `delivery`(product_id,pr_name,pr_price,pr_size,user_id, dt)
SELECT `product_id`,`pr_name`,`pr_price`,`pr_size`,
`userid`, NOW()
FROM `shopping_cart` WHERE `userid` = $uid";
To insert current date only use CURRENT_DATE()
$sql="INSERT INTO `delivery`(product_id,pr_name,pr_price,pr_size,user_id, dt)
SELECT `product_id`,`pr_name`,`pr_price`,`pr_size`,
`userid`, CURRENT_DATE()
FROM `shopping_cart` WHERE `userid` = $uid";
These queries assume you have a column named dt in your delivery table. Please change column name if different in your schema, or add a date or datetime column in your table if you do not have any yet
You dont need to do the date capture in PHP, as long as you want the date to be the date as at time of execution of the query. You can use the MySQL NOW() function, just add it to the inner query in the correct column to match the outer queries columns.
$sql="INSERT INTO `delivery` (product_id,pr_name,pr_price,pr_size,user_id, PR_DATE)
SELECT `product_id`,`pr_name`,`pr_price`,`pr_size`, `userid`, NOW()
FROM `shopping_cart` WHERE `userid` = $uid";
If you want to insert your own date then use as per below-
$date = date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $date)));
$sql="INSERT INTO `delivery`(product_id,pr_name,pr_price,pr_size,user_id, your_date_column)
SELECT `product_id`,`pr_name`,`pr_price`,`pr_size`,
`userid`, '$date'
FROM `shopping_cart` WHERE `userid` = $uid";
If you want to put current date then use as per below-
$sql="INSERT INTO `delivery`(product_id,pr_name,pr_price,pr_size,user_id, your_date_column)
SELECT `product_id`,`pr_name`,`pr_price`,`pr_size`,
`userid`, CURDATE()
FROM `shopping_cart` WHERE `userid` = $uid";
Note: If you want to insert with time then use now().
I cant understand your clearly. Normally, we insert current date like
curdate()
sysdate()
Use now() in your query to get the current date.
First of you have to check whether you have column for current date or not in your database table. If not then you have to add a column to store current date and use that column in your query.
You can use timestamp /datetime / now() function to store current date(choose one according to your requirement)
$sql="INSERT INTO `delivery` (product_id,pr_name,pr_price,pr_size,user_id, curr_date)
SELECT `product_id`,`pr_name`,`pr_price`,`pr_size`,
`userid`, timestamp
FROM `shopping_cart` WHERE `userid` = $uid";

Count number of logins per day in PHP Timeclock (PHP Mysql)

What are the mysql codes to count the number of logins per day in PHP Timeclock?
timestamp bigint(14) is used and I have no idea how to separate them by date.
How do I count the number of ROWS per day?
Here's the command to create the table info:
CREATE TABLE info (
fullname varchar(50) NOT NULL default '',
`inout` varchar(50) NOT NULL default '',
timestamp bigint(14) default NULL,
KEY fullname (fullname)
) ENGINE=MyISAM;
Sorry I'm just a newbie trying to understand php and MySQL.
Anyway, I can add either of the two in info table:
timestamp timestamp default NULL,
or logindate date default NULL,
Suppose I have this portion of the code saved in a php file, how can I modify it so date or timestamp is inserted in info table everytime a user logs in?
$time = time();
$hour = gmdate('H',$time);
$min = gmdate('i',$time);
$sec = gmdate('s',$time);
$month = gmdate('m',$time);
$day = gmdate('d',$time);
$year = gmdate('Y',$time);
$tz_stamp = mktime ($hour, $min, $sec, $month, $day, $year);
if (strtolower($ip_logging) == "yes") {
$query = "insert into ".$db_prefix."info (fullname, `inout`, timestamp, notes, ipaddress) values ('".$fullname."', '".$inout."',
'".$tz_stamp."', '".$notes."', '".$connecting_ip."')";
} else {
$query = "insert into ".$db_prefix."info (fullname, `inout`, timestamp, notes) values ('".$fullname."', '".$inout."', '".$tz_stamp."',
'".$notes."')";
}
$result = mysql_query($query);
Since it's a BIGINT (why, btw?) I assume it's a UNIX Timestamp.
I haven't tested this, but something along the lines of this should work:
SELECT DATE(FROM_UNIXTIME(timestamp)) AS date, COUNT(*)
FROM info
GROUP BY date
You might wanna just store the timestamp as a TIMESTAMP column type, and then just use DATE(timestamp) to group by date.
Add a column of date only (without the time) and use this:
SELECT COUNT(*), dateColumn FROM info WHERE fullname='{The user full name}' GROUP BY dateColumn

how to retrieve count from mysql between 2 hours

Consider the following table:
CREATE TABLE `trans` (
`transid` varchar(255) NOT NULL,
`affid` varchar(255) NOT NULL,
`timestamp` varchar(255) NOT NULL,
UNIQUE KEY `transid` (`transid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
and PHP code:
case "today":
$sale=[];
for ($i = 0 ; $i < 23 ; $i++) {
$hours[]= $i;
$clicks[$i]=$api["clicks"][$i];
}
break;
I want to add into the $sale array today's count of sales for each hour. Something like: $hours[5] = select count(*) from trans where .. date is between today's 04:59:59 - 06:00:00.
First of all, if you are trying to use unix timestamps for your timestamp field, stop it now. You are already making your life painful. Use a MySQL timestamp field. There are honestly very few use cases where it is a good idea to use a unix timestamp field.
If you had a timestamp field you could do something like
SELECT HOUR(`timestamp`) AS `hour`, SUM(`transid`) AS `transaction_count`
FROM trans
WHERE `timestamp` LIKE CONCAT(DATE(NOW()),'%')
GROUP BY `hour`
ORDER BY `hour` ASC
That would give you the sales count for every hour of the current day. Make sure you add an index on timestamp for optimal query performance.
If you don't have a timestamp, then you need to utilize extra FROM_UNIXTIME() conversions, which would prevent you from being able to use an index on timestamp
Something like this:
<?php
$from=strtotime("".date("Y-m-d")." 04:59:59");
$to=strtotime("".date("Y-m-d")." 06:00:00");
?>
"SELECT * FROM `your_table`
WHERE `date` > '".$from."'
AND `date` < '".$to."'"
maybe?
You can use gmdate() if you need the current UTC time instead of the local time which you get with date().

Timestamp comparison to delete when mysql timestamp > 20 minutes

I want to do something which is not complicated but I do not manage to succeed even after I tried a lot of things....
First of all, I have a database mysql with a row of timestamp type. I insert into it elements with a date like this:
$date = date('Y-m-d H:i:s', time());
$req =mysql_query("INSERT INTO my_table (id, departement, voie, date,message)
VALUES ('', '$departement_token', '$voie_token','$date' , '$message_token')");
The result of this code line is a date element like this : 2012-07-19 20:18:17
I want to delete all elements with a date > current date + 20 minutes and I do not succeed...
I tried this:
mysql_query("DELETE FROM my_table WHERE DATE_SUB(date,INTERVAL 20 MINUTE) ORDER BY date");
And this:
$req=mysql_query("DELETE FROM my_table WHERE date >= TIMESTAMPADD(MINUTE,-20,NOW())
ORDER BY date");
And this:
$timePlus20min = time() + 1200;
//et on compare les deux dates
$req = mysql_query(
"DELETE FROM my_table WHERE UNIX_TIMESTAMP(date) >= '$timePlus20min' ORDER BY date");
But none of this works. Could you help me please, I think it's not too difficult but I'm out of ideas...
$period=date('Y-m-d H:i:s',time()-(60*60*6)); // 6 hour before
"SELECT * FROM limitlessisa WHERE UNIX_TIMESTAMP(REG) > UNIX_TIMESTAMP('$period')";
REG // timestamp row name
This is working. 6 hours before listing data
In all your queries you forgot the WHERE keyword so they are syntactically wrong. Also, the ORDER BY statement has no effect as you are not executing a SELECT query. There is no result that could be ordered. Instead, a single table DELETE query returns a count of the number of deleted rows.
DELETE FROM my_table WHERE date >= DATE_ADD(NOW(), INTERVAL 20 MINUTE);
As I do not know your table structure, I tried this query with the following table:
CREATE TABLE `datetest` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;
try this :
$req=mysql_query("DELETE FROM my_table WHERE date <= ".date("Y-m-d H:i:s", mktime(date("H"), date("i")-20, date("s"), date("m"), date("d"), date("Y")));
Bonne chance à toi / Good luck
Try this:
DELETE FROM my_table WHERE UNIX_TIMESTAMP(date) > 60 * 60 * 20 + UNIX_TIMESTAMP();

Storing the date in database

Well I have a task to store "quotes" into a database (Already done this) and display them & sort them out for the most recent quotes. I'm assuming to get the "most recent", I'd need to store date/time of the submitted quote.
I am new to PHP and trying to learn, so I don't know how to exactly do this.
Here is the PHP for adding the quotes to the database. There are two columns in the table called "quotes" and "id". I'm guessing I will also need to make a column for the date too?
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
How would I also insert the date?
use CURDATE() if you want to insert the current date
example:
$query_auto = "INSERT INTO tablename (col_name, col_date) VALUE ('DATE: Auto CURDATE()', CURDATE() )";
but if you wqant it manually then should use this:
$query_manual = "INSERT INTO tablename (col_name, col_date) VALUES ('DATE: Manual Date', '2008-07-04')";
UPDATE
CREATE TABLE auto_ins
(
`MySQL_Function` VARCHAR(30),
`DateTime` DATETIME,
`Date` DATE,
`Time` TIME,
`Year` YEAR,
`TimeStamp` TIMESTAMP
);
INSERT INTO auto_ins
(`MySQL_Function`, `DateTime`, `Date`, `Time`, `Year`, `TimeStamp`)
VALUES
(“CURDATE()”, CURDATE(), CURDATE(), CURDATE(), CURDATE(), CURDATE());
If you only want the most recent quotes, you can simply sort your result set by their id DESC assuming the id is an auto-incremented value.
Yes, you need a third column lets say most_recent (defined as date or datetime) :
mysql_query("INSERT INTO entries (quote, most_recent) VALUES('$quotes', now())")
You will need at least couple of tables who submitted the quote and the quote table itself.
create table users(id int primary key not null, username varchar(32),pwd varchar(32));
you can add any info to that table like email address and so on.
create table quotes (
id int not null ,
user_id integer,
quote_text varchar(256),
inserted_date timestamp default current_timestamp ,primary key (id));
alter table quotes add constraint fk_users foreign key(user_id) references users(id);
Otherwise feel free to modify them.
It's not about php here its about DB design in general.
Use this code:
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = now().' - '.mysql_real_escape_string($quote);
// THIS WILL ADD THE DATE AND TIME TO YOUR $quotes STRING.
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());

Categories