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.
Related
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.
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
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');
I'm trying to get an SQL query with PHP to populate various fields in a form so they can be edited by a site administrator. Those two fields are date and time.
I'm using the two input types 'date' and 'time'. The date field is populating perfectly. The time field is coming up blank. The data for both is coming from the same SQL query. I'd like them both to display within the intended format for each field. (I'm using Chrome for this as I know the field types aren't supported by all browsers).
//Queries
$pull_game = "select datetime, city, opponents.opponent_id, game_type, tourn_name, time, home_score, vis_score, day_of_week, month, day, year, parks.park_id, park, win, loss, tie, result from games, opponents, parks, tournaments where opponents.opponent_id = games.opponent_id and parks.park_id = games.park_id and tournaments.tourn_id = games.tourn_id and game_id= ".$_POST['game_id'] . ";";
$game_stats = mysqli_query($con,$pull_game) or die("ERROR: $pull_game. ".mysqli_error());
$game = mysqli_fetch_array($game_stats);
//Display data
<input type='date' name='date' value=<?= $game['datetime']?>>
<input type='time' name='time' value=<?= $game['datetime']?>>
I've tried eliminating the date field to see if the time field would work, but it still came up blank. I've had no luck researching this - most of the content I find is for updating the DB with datetime data. I'm looking for the opposite (sort of).
Any help would be appreciated.
//Queries
$pull_game = "select date(datetime) as d, time(datetime) as t, city, ..."
//Display data
<input type='date' name='date' value=<?= $game['d']?>>
<input type='time' name='time' value=<?= $game['t']?>>
should do the trick. Valid date and time formats for HTML5 inputs are described in https://www.w3.org/TR/html5/infrastructure.html#dates-and-times - essentially it's YYYY-MM-DD for "date", and HH:MM:SS for "time" inputs. Conveniently, this is exactly the output MySQLs date() and time() functions yield (cp. http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html).
you could use a substr function to escape the chracters from the date and add only the time or you can also try using the strtotime function too, to convert the data type you are getting from the query and put it into the fields you need
$date2=date('Y-m-d', strtotime($date));
check the strtotime function here
Also I don't think there is a input type="time" so, check the existsent input types
I have been trying to follow the example shown from this link below:
PHP mysql insert date format
This is my code sample below:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
/** Variables */
$pdate = isset($_POST['pdate']) ? $_POST['pdate'] : '';
$org = mysqli_escape_string($dbcon, trim($_POST['org']));
$city = mysqli_escape_string($dbcon, trim($_POST['city']));
$state = isset($_POST['state']) ? $_POST['state'] : '';
$rio = mysqli_escape_string($dbcon, trim($_POST['rio']));
/** Query */
$q = "INSERT INTO `survey` (id, pdate, org, city, state, rio, date_created)
VALUES (NULL, STR_TO_DATE('$pdate', '%M %d, %Y'), '$org', '$city', '$state', '$rio', NOW())";
?>
/** Changing Datepicker Value **/
jQuery(document).ready(function($) {
/** Datepicker for the Form */
$('.selector').datepicker('option', 'dateFormat', 'yy-mm-dd');
});
$pdate = "2015-09-28"; Displays like that according to the <?php echo format ?>
There are two queries that you are using, should I use the STR_TO_TIME() or FROM UNIXTIME()
When I try and follow the 3rd step:
$dt = DateTime::createFromFormat('m/d/Y', $_POST['pdate']);
$pdate = $dt->format('Y-m-d');
After submitting the form, I get undefined variable index.
What is it that I am now missing?
You didn't post the most important information - actual error message - so I can only guess, what's wrong. These are my guesses:
If undefined index is pdate, than you don't have such form control. That could be the raeson, why you have "0000-00-00" as a date in your DB
You have configured Datepicker to output date in a format yy-mm-dd, but you're parsing it as %M %d, %Y in MySQL function STR_TO_DATE or m/d/Y in PHP DateTime's method createFromFormat. That doesn't make a sense.
Since yyyy-mm-dd is MySQL's native format to express a date, you don't need any conversion at all. Just save into a DB what you get from Datepicker.
So I would start with this:
Check what you're getting from your form in PHP, e.g. print what's in $_POST array: var_dump($_POST)
Check if there is a key pdate and contains date in format yyyy-mm-dd
Save it to DB. You're done.
The easiest way to Insert Date Format is to do the following using jQuery Date Format See - http://api.jqueryui.com/datepicker/#option-dateFormat
`jQuery`
$( ".selector" ).datepicker({
dateFormat: "yy-mm-dd"
});