I've built a small application which has User Management, a frontend console to enter data and a backend console to control parts of the frontend. The frontend adds rows to a MySQL database which are timestamped. The backend needs to be able to select rows from the database between X and Y dates.
Everything works so far, except the date part which I'm really struggling with.
The frontend SQL input looks like this (simplified with spurious code removed):
$date = time();
$top_level_category = $_POST['top_level_category'];
$sub_level_category = $_POST['sub_level_category'];
$company = $_POST['company'];
$agent_name = $_POST['agent_name'];
$ticket_id = $_POST['ticket_id'];
$sql = "INSERT INTO dacc_data ("
. "id, top_level_category, sub_level_category, "
. "agent_name, date, ticket_id, company"
. ") VALUES ("
. "NULL, '$top_level_category', '$sub_level_category', "
. "'$agent_name', FROM_UNIXTIME('$date'), '$ticket_id', '$company'"
. ")"
;
$result = mysql_query($sql) or die (mysql_error());
That seems to work ok, the timestamp is being picked up and added to a DATETIME column in my table. It displays as dd/mm/yyyy hh:mm:ss within the database.
So ... my first question is - is this the right way to do it?
The second question being, what sort of SQL statement would I need to pull out an array of rows between X and Y date.
Apologies if this is rambling a bit, hope it's clear but if you need more information let me know.
MySQL datetime should be formatted with dashes:
YYYY-MM-DD HH:MM:SS
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
Then you can query for date ranges a couple of ways:
select *
from table
where date >= '[start date]' and date <= '[end date]';
or
select *
from table
where date between '[start date]' and '[end date]';
where "table" is the name of your database table and "date" is the name of your datetime field.
You are correct. I can confirm that the Database has "YYYY-MM-DD HH:MM:SS" - I am using SQLWave editor for browsing the DB quickly, it auto-formats the DATETIME column.
// Initial questions still stand :)
Or not, just noticed you updated the answer - thank you very much! I had actually tried that very same query several times to no avail, mainly because my WHERE was specifying the date format incorrectly. Misled by SQLWave :(
Back to using command line from now on !!!
"what sort of SQL statement would I need to pull out an array of rows between X and Y date?"
SELECT * FROM `dacc_data` where `date` between "2008-11-01" and "2008-12-01"
Related
I don't have too much experience with the PHP programming language, so I ask you for help solving a small problem.
I have several users in the tabele with their data and one column that lists the date when they need to report to the interview.
I need a sql query syntax to check the following:
Does the database have a user whose date in the table is the same or larger than it currently is. If a user is found, then my program will send an email to remind him.
I will use CRON JOB after to refresh the index.php, thats okay, but bothers me the most that I don't know the date comparison syntax.
Otherwise the date in mysql database for each user is entered in the format 2020-02-15
$datenow = date("Y-m-d");
echo $datenow;
$sql = "SELECT * FROM 'users' WHERE 'report_date' >= '".$datenow."'";
if ($result = mysqli_query ($con, $sql)) {
if (mysqli_num_rows($result)> 0) {
while($rows = mysqli_fetch_assoc ($result)) {
$id = $row['id'];
blablablabla
}
bothers me the most that I don't know the date comparison syntax
You seem to be looking for MySQL date function current_date(), which is the equivalent of php function call date("Y-m-d"):
SELECT * FROM users WHERE report_date >= current_date;
Side note: do not surround the column names with single quotes, otherwise it turns it to a literal string, so you end up comparing string 'report_date' with the date, which will not do what you want. Same goes for the table name, that should not be single quoted either.
I am trying to convert three separate database columns into a date (day,month,year) and calculate the age so only users over the age of 15 or 18 can purchase certain products. The code below doesnt work as it echoes '0 days, 0 months, 0 years' and still adds the product to the basket. Which means the age calculation doesnt work, and my first if statement doesnt work either.
<?php
$username = $_SESSION['solentuser'];
echo "$username's account!<br>";
$conn = new PDO("mysql:host=localhost;dbname=u;","u","p");
$productID= htmlentities($_GET['ID']);
//startdate
$result=$conn->prepare("SELECT * FROM users WHERE username=:username");
$result->bindParam(":username",$username);
$result->execute();
$row=$result->fetch();
$birthdate = $row['yearofbirth'] . $row['monthofbirth'] . $row['dayofbirth'];
$presentdate = date('Ymd');
$birthday = new DateTime($birthdate);
$currentdate = new DateTime($presentdate);
$age = $birthday->diff($currentdate);
echo $age->format('<br>%d Days %m Months %y Years<br>');
//enddate
$results=$conn->prepare("SELECT * FROM products where ID=:productID");
$results->bindParam(":productID",$productID);
$results->execute();
$row=$results->fetch();
if($row['agelimit'] <= $age){
if($row['stocklevel'] >= 1){
$result=$conn->prepare("INSERT INTO basket(productID,username,qty) values(:productID,:username,1)");
$result->bindParam(":productID",$productID);
$result->bindParam(":username",$username);
$result->execute();
$result=$conn->prepare("UPDATE products SET stocklevel=stocklevel-1 WHERE ID=:productID");
$result->bindParam(":productID",$productID);
$result->execute();
echo "You have successfully added this product to your basket!";
}
else{
echo "This product is out of stock!";
}
}
else{
echo "You are not old enough to purchase this product!";
}
//print_r($conn->errorInfo());
?>
any suggestions as to where the error is? i have read that it is possible to write an if statement inside an if statement, so why does this one not work?
thank you!
I'd echo out $birthdate and verify there's a valid date there. (We aren't getting back single digits, a date of 2009-05-04 getting represented as '2009', '5' and '4' such that when we concatenate them, we get 200954, or maybe extra spaces. (We're not seeing the datatypes of the three separate columns.)
We might try adding some delimiters in there, so we'd get 2009-5-4, likely we could get that converted into a DateTime, using the correct format string.
If I had separate values for month, day and year, I would use PHP mktime, and then create a DateTime object from that.
(MySQL does provide a DATE datatype that allows for a very large range of valid dates, and doesn't allow invalid dates to be stored. Storing three separate columns to represent a single date just smells like the wrong way to do it. (If I actually needed the separate month and day columns (to allow indexing for some queries), I would add those in addition to the birthdate DATE column, not in place of it, with triggers to keep the values in sync with the birthdate column.)
Also, $age is a DateInterval object. You seem to be aware that we can use the format method to extract integer number of years.
$age_yrs = $age->format('%y');
We're guessing that the database column age_limit is integer years.
if( $row['agelimit'] <= $age_yrs ) {
Right before that if statement, we can confirm that what we think to be true is actually true...
echo " age_yrs=" . $age_yrs;
echo " row_age_limit=" . $row['age_limit'];
Looking closely at the debugging output helps us identify if the problem is before the if statement or after, so we aren't chasing down a problem in a section of code where there isn't a problem, the problem is somewhere else, on a preceding line.
I encourage you to develop the skills needed to debug programs that you write. It seems like you are making some (wrong) assumptions about what the variables are containing.
Adding echo and var_dump during development is a first step in verifying that what you think to be true is actually true.
I'd go as far as recommending that you look at every line of code you write as possibly going wrong, especially in edge cases.
https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
(StackOverflow is a question/answer community, not a debugging service.)
I have been trying to pull records based on a specified date. In the DB I have a column where I store unix timestamps. The user has the option to select records based on a date. The user inputs: 08/08/2016 (for example)
How would I write my SQL statement to handle this?
$query .= "`".$o."` = '".date("Y-m-d",strtotime($v))."' AND ";
Here we see the line where part of the SQL statement is built, because more than one column could be targeted by the user during their search request.
Somehow I need to be able to turn $o (which is a column storing unix timestamps) into the Y-m-d format for comparison, as shown above and make this work in an SQL statement.
Any help would be appreciated.
EDIT
Here is what worked for me:
$query .= "".$o.">= '".strtotime($v)."' AND".$o."< '".(strtotime($v)+(24*60*60))."' AND ";
You can do something like:
"WHERE DATE(`$o`) = '".date("Y-m-d",strtotime($v))."'"
However this won't use indexes, so if you have a large table it will be slower. If you want to be able to use indexes you can do:
"WHERE `$o` >= ".date("Y-m-d",strtotime($v))."
AND `$o` < ".date("Y-m-d",strtotime($v))." + INTERVAL 1 DAY"
You can also try this approach and use UNIX_TIMESTAMP on MySQL.
$v = '2016-08-04';
$query .= "'".$o."' = UNIX_TIMESTAMP('$v') AND ";
I have a input field which takes input in the time format 'H:i A' and should store in the mysql database of time type data.
I have converted the input by the dateTime function which looks like-
$sat_opened = DateTime::createFromFormat( 'H:i A',$_POST['sat_opened']);
$sat_opened_new = $sat_opened->format('H:i:s');
And query used to insert is -
mysqli_query($connect, "INSERT INTO biz_hours VALUES(DEFAULT, '$bid', 'Sat', '$sat_status', '$sat_opened_new', '$sat_closed','')")
Others Data are being inserted but for opened column it always inserts 12:00:00 . If i print the converted time (echo $sat_opened_new) then it prints time fine that should be in the MySQL time format like - 08:50:00 or 17:30:00
What problem actually is there? Please help me to find out. Thanks
It appears that you're successfully able to insert a date directly through phpMyAdmin: INSERT INTO biz_hours (opened) VALUES ('12:34:56') . So you need to work back through your PHP query and debug it. Start with the minimal working mysqli_query and begin adding back other fields (biz_id, day, status, etc.) until you encounter the problem again. Perhaps one of your variables is not properly set.
I have the same problem but a little different from Neil problems (Error when trying to insert date into datetime column),
Neil want to get now date time so he can use CURRENT_TIMESTAMP or GETDATE().
My question is, how if I have string of date like:
$date = '2011-03-29';
then I want to insert into SQL Server database using a stored procedure with PHP.
insert into tbl(date)
values($date)
Can anybody help? Thanks
Just fyi, I have
SQL Server table:
CREATE TABLE tbl
(
date datetime
)
Stored procedure:
create procedure sp_insertdate
(#date datetime)
as
begin
insert into tbl(date) values(#date)
end
PHP code:
<?php
$date = '2011-03-29';
include("con.php");
$query = mssql_init("sp_insertdate");
mssql_bind($query, "#date", &$date, SQLINT4); //sqlint4 for datetime
mssql_execute($query);
?>
The result is 1900-1-1,
I have tried to send the varchar (in php) first then convert to the datetime (in stored procedure) but there is some error.
Really I'm stuck.. any idea for this problem?
I just want to insert string 2011-03-29 into a SQL Server datetime column using a stored procedure from PHP. I'm sorry because I can't speak English fluently
Whenever I've had a problem like this (using mysql), I just had to add the time (midnight) onto the date so that it can recognize it as the datetime that it's expecting. Try this:
$date = '2011-03-29';
$date .= ' 00:00:00';
Then process the rest as you would. This works for mysql, maybe sql-server needs it like this too.
i got answer from my friends,
just put
mssql_bind($query, "#date", &$date, SQLCHAR); //not sqlint4 for datetime but just sqlchar or sqlvarchar
however many thanks to Groovetrain, i can put also
$date='2011-03-29 00:00:00'
then put
mssql_bind($query, "#date", &$date, SQLCHAR,false,false,19); //19 length of date string