Fetching data via two dates in php sql - php

This dates get method to get date another page
$fromdate = $_GET[fromDate];//14/10/2021
$todate = $_GET[todate];17/10/2021
$collect_Amt = $conn->query("SELECT lvlCol_amt,lvlCol_type,lvlCol_directEarn_perct,lvlCol_directEarn_amt,lvlCol_associateId,lvlCol_collectId,lvlCol_dateTime from `t_lvl_collect` where lvlCol_dateTime between '$_GET[fromDate]' AND '$_GET[todate]' AND lvlCol_associateId = $MemberId ORDER BY lvlCol_dateTime DESC");
but return data is 15/10/2021,15/10/2021 And 16/10/2021
17/10/2021 not disply please
help?

If youe date is not in Y-m-d H:i:s format please add # before data
please check below w3school link for more ref.
https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_between_date&ss=-1
so your query like
SELECT lvlCol_amt,lvlCol_type,lvlCol_directEarn_perct,lvlCol_directEarn_amt,lvlCol_associateId,lvlCol_collectId,lvlCol_dateTime
from `t_lvl_collect`
where lvlCol_dateTime between **#date_1** AND **#date_2** AND lvlCol_associateId = $MemberId ORDER BY lvlCol_dateTime DESC
NOTE: replace date_1 and date_2 with your variable. add d/m/y and m/d/y both formate will work.

Related

Check if the time is more than 24h and show it

I have in my MSSQL database a column with datatype of datetime which contains some dates in this format 2021-01-11 19:58:04.277.
This is a voting system, the idea is that the users can only vote once every 24 hours.
Every time they vote this table is updated with a new record and a new date is added with the corresponding user.
I want to display a message that says how many hours left to place the next vote.
This is the code I am trying to use:
/**
* Get Votes Time
*
*/
public function getVoteRemainingTime($account) {
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$sql = "SELECT VoteDate FROM dbo.vote WHERE Account = :account ORDER BY logid DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':account' => $account));
$voteDate = $query->fetch(PDO::FETCH_OBJ);
$timeLeftVote = strtotime($currentTime) - strtotime($voteDate->VoteDate);
if($timeLeftVote > 86400) {
return '<strong>Vote Available!</strong>';
} else {
return $timeLeftVote;
}
}
But it is displaying the wrong information. What I am doing wrong? I would appreciate your help.
Thanks!
you need declare format parameter of the date() like date('Y-m-d H:i:s')
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$timeLeftVote = strtotime($currentTime) - strtotime('2021-01-11 19:58:04.277');
if($timeLeftVote > 86400){
echo 'Vote available';
}else{
echo $timeLeftVote;
}
Instead of SELECT VoteDate FROM dbo.vote
Can you do the calculation on the time difference at source in the database using
SELECT VoteDate, DATEDIFF(HOUR, VoteDate, GETDATE()) as HourDifference from dbo.vote
As I cannot check your database query, I only checked the rest of the code and it seems to work (as Fikri F mentioned in the comments of this post) if I replace $voteDate->VoteDate by a static date.
So please provide more information. You could output the current time and the previous vote time from the database as strings, and for both dates as well the result of strtotime, and in the end the result of the method. Then please explain, what the wrong behaviour is. By this, we can narrow down the problem either to the DB query or to the PHP code.
(I would write this as a comment, but I have not enough reputation.)

submitting PHP - HTML DATE to MySQL DATE

i would like to help with my code how to edit HTML input date into MySQL TIMESTEMP format cause my SQL code is invalid and data are not added to my database, Thanks for help
also i asking to check this code on bottom cause 2nd SQL deppends on 1st SQL, thanks
if (isset($_POST['pridaj_anime_submit'])) {
$sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
VALUES ('$_POST[nazov]', '$_POST[rok]', '0', '$_POST[pocet]', '8', '10', '$_POST[preklad]', '$_POST[stav]')";
mysqli_query($connect_to_db , $sql_vloz_anime);
$sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$_POST[nazov]'";
$run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($sql_ziskaj_a_id_pridaneho_anime);
$a_id_ziskane = "";
while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
$a_id_ziskane = $db_data['a_id'];
}
$sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
VALUES ('$a_id_ziskane' , '$_POST[obrazok]', '$_POST[zaciatok]', '$_POST[koniec]', '$_POST[cas]', '$_POST[akihabara]')";
mysqli_query($connect_to_db , $sql_vloz_anime_info);
}
$input_date=$_POST['date'];
$date=date("Y-m-d H:i:s",strtotime($input_date));
This will convert input date into MySQL Timestamp compliant format.
Please DO NOT put POST values directly in your queries. Your website or web application will be hacked in no time through SQL Injections.
MySql datetime considered yyyy-mm-dd h:i:s format.
Your input date is like dd-mm-yyyy h:i:s and so on.
Then use convert date to yyyy-mm-dd h:i:s. Read strtotime manual.
For e.g.
$inputDate = '06-06-2017 05:21:34';
$mysqlDate = date("Y-m-d H:i:s",strtotime($inputDate));
// MySql Query.
INSERT INTO table_name SET `your_field`='$mysqlDate'

Trying to make a stored Datetime value shorter with SQL Convert function

I'm new to using the convert function. I'm trying to make a datetime value from my table shorter. Currently my datetime values look something like this, 2016-10-14 16:51:41, but I'd like to make it look something like mm/dd/yy.
I don't know if this is the right approach (must not be since it doesn't work), but I've generated a query using the convert function and then fetching the data with a mysqli_fetch_array.
Here's the code I'm using:
$sql = "SELECT id, time, CONVERT(VARCHAR(11), time) as something FROM tableName";
$query = mysqli_query($db, $sql);
$statusnumrows = mysqli_num_rows($query);
// Gather data about parent pm's
if($statusnumrows > 0){
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$time= $row["time"];
}
}
Time is the name of the column which has the datetime type.
Thanks in advance, for suggestions/advice.
You should store datetime in your DB in proper data types like datetime etc.
As I can see you are using PHP, if you need to OUTPUT this datetime in some interface (f.e. HTML page), you should use PHP functions to convert date in format you need. That is the good practice
DB should STORE the data but formatting is front-end problem.
Simple example of strtotime() and date():
$Date = "2016-10-15";
$newDate = date("m/d/Y", strtotime($Date));
You can read docs on the PHP site: strtotime and date
If 2012+ you could use format (not very efficient but does offer some other possibilities)
Declare #Date DateTime = GetDate()
Select UsingFormat = Format(#Date,'MM/dd/yy')
,UsingConvert1 = convert(varchar(10),#Date,1)
,UsingConvert101 = convert(varchar(10),#Date,101)
Returns
UsingFormat UsingConvert1 UsingConvert101
10/15/16 10/15/16 10/15/2016
Use style 1 in Convert function for mm/dd/yy format
select CONVERT(VARCHAR(20), [time],1)
From yourtable
If you want mm/dd/yyyy format then use 101 style
select CONVERT(VARCHAR(20), [time],101)
From yourtable
MSDN link for Convert function with various style : CONVERT

Get date and time retrieved from database into a datetime input

I'm trying to retrieve a Datetime value from my database and place it in an html input with a date type but it doesn't show anything.
$resQuery = mysql_query("SELECT * FROM reserveringen WHERE id = $ID");
while ($resInfo = mysql_fetch_array($resQuery))
{
$dateTime = $resInfo[3];
}
<?php echo "<input name='dateTime' type='datetime-local' value='$dateTime'"?>
Also when I F12 I get this error: The specified value "2525-0505-16161616 0606:0505" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".
This fixed it for me guys!
I changed my query to:
SELECT *, DATE_FORMAT(Datum, '%Y-%m-%dT%H:%i') AS Datum_conv FROM reserveringen WHERE id = $ID
The problem is that when you was writing data into database you used wrong date format. Look carefully at datetime value:
2525-0505-16161616 0606:0505
It must be
25-05-16 06:05
What you did when saving data is using these date format:
date('dd-mm-yyyy HH:ii')
instead of this
date('d-m-Y H:i');

Filter database fields by date

I have a page that shows user activity, I have built a form where the user can filter this by date.
Here is the form
<form action='filter_activity.php' method='get'>
From: <input type='text' name='from' value='dd/mm/yyyy'>
To: <input type='text' name='to' value='dd/mm/yyyy'>
<input type='submit' value='Filter'>
Here is the filter_activity.php page:
$from=$_GET["from"];
$to=$_GET["to"];
$result=mysql_query("SELECT * FROM member WHERE personID=$user AND created between $from and $to ");
However this shows nothing, can anyone help?
Your posted dates are in invalid format for DB use. You need to convert them before use in DB.
$from = DateTime::createFromFormat('d/m/Y', $_GET['from']);
$to = DateTime::createFromFormat('d/m/Y', $_GET['to']);
$sql = "
SELECT *
FROM member
WHERE personID = $user AND created BETWEEN '%s' AND '%s'
";
$sql = sprintf($sql, $from->format('Y-m-d'), $to->format('Y-m-d'));
Plus, you should check if $_GET keys exists and after that, check if $from and $to are DateTime object, and not false.
you need to cast it to date like:
$result=mysql_query("SELECT * FROM member WHERE personID=$user AND created BETWEEN DATE('$from') AND DATE('$to')") or die(mysql_error());
from the site :
For best results when using BETWEEN with date or time values, use CAST() to explicitly
convert the values to the desired data type. Examples: If you compare a DATETIME to two
DATE values, convert the DATE values to DATETIME values.
If you use a string constant such as '2001-1-1' in a comparison to a DATE,
cast the string to a DATE.
Pass the correct date format to the DB:
$from = date('Y-m-d', strtotime(str_replace('/', '-', $_GET["from"])));
$to = date('Y-m-d', strtotime(str_replace('/', '-', $_GET["to"])));
$result = mysql_query("SELECT * FROM member WHERE personID=$user AND created BETWEEN '$from' AND '$to'");
Really think about changing the format in your form. I would use a date picker, either year/month/day dropdowns or javascript.
Also, read the other comments about quoting, SQL injection, etc. And get off of mysql_* functions.

Categories