I have several db calls in my site with bind_variables that works fine. But, I can find the correct sign for Date in the documentation, for the command:
$query->bind_param("ssi",...);
I don't want to do something like:
$db->query('SELECT item FROM table WHERE something='.$something);
Since this is string manipulation, not binding. (In binding the query is left with the "?" and that makes the queries faster because the DB sees them the same only with different cariables.)
If I wasn't very clear, I want to do the same as this only with a date variable type.
Some extra information to my comment given above:
If I do understand correctly have a
look at:
Using Mysqli bind_param with date and time columns?.
It looks like you can just treath it
as a string.
If you want to do it with bind_param it is the only way I know to do it and I don't see any problems. If mysql receives a wrong formatted date it will insert a 0000-00-00 value to your table.
Can you tell me what you think could be a problem? If you insert it as a normal query you also use the same syntax as a String.
For dates, you will have to format them before calling bind_param:
$query->bind_param('s', $date->format('Y-m-d H:i:s')); // assuming $date is a DateTime object
Dates should be bound as strings in a format MySQL accepts (yyyy-mm-dd).
Related
I have a small problem. I'm using PHP with Oracle (new to the Oracle by the way).
In my database there's a DATE field called NEXT_START_DATE and it's value is
25.12.2013 04:05:01
as you can see below.
The thing is I can get date values just fine in my web page, but couldn't see anything like a time, if you can see below image, it only returns 25/12/2013.
I know that people suggested to use pl/sql functions like
to_date()
or
to_char()
but is this possbile using just php? I really can't interfere the SQL. Any help would be awesome, Thanks in advance.
In ADOdb, make sure to set the format before connecting:
$db = ADONewConnection("oci8");
// $db->debug = true;
// Date format is set before connecting.
$db->NLS_DATE_FORMAT = 'DD.MM.YYYY HH24:MI:SS';
Courtesy: http://board.issociate.de/thread/192412/OCI_ignoring_NLS_DATE_FORMAT_parameter.html
You can use SQL functions in your queries as well.
For example,
SELECT TO_CHAR(next_start_date, 'YYYY-MM-DD HH24:MI:SS') FROM mytable
and you'll get the date in the format you specified.
As #Maheswaran Ravisankar pointed out, there is NLS_DATE_FORMAT as well, but if you set it, that format is used for all queries (that do not specify to_char). I always use to_char in all my selects, because it allows me to specify an individual format for each query.
I have a problem in storing the $date variable in the database column called data of type varchar(50)
This is the code of the date variable
$date = date("Y-m-d");
echo $date;
and this is the code that stores it into the database (notice that the date is the same one)
what is the problem with my code
$sql="INSERT INTO
Students(FirstName, LastName,gender,Major,Favorite_courses,GPA,date)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[sex]','$_POST[major]',
'$_POST[favorite]','$_POST[GPA]','$date')";
Change the column type to DATE and then use SYSDATE as the value to input the current date/time on the SQL server.
Also, read up on SQL injection!
Technically your code should work, but in practice it will undoubtedly fail.
For starters you should never put POST data directly into your database. Depending on what's in that data, it will at the least break your SQL statement. It could also destroy your database if someone entered some SQL into a POST variable.
Don't do it that way. You need to sanitize any data coming from the outside world before inserting it into the database. There are several PHP database classes that do this for you. I like PDO.
Also, write better PHP by using $_POST['favorite'] instead of $_POST[favorite]. What happens if you do this in your code somewhere define('favorite', 'foobar')?
What happens is that your code will than look for $_POST['foobar'] instead of $_POST['favorite'].
You really need to work on your knowledge of PHP and SQL before rolling anything out into the wild, or you're going to have problems. But keep plugging along, you'll get it.
Aside from the, already several times mentioned, SQL injection: use date('c') (or more specifically: ISO8601 notation). That will result in code like:
$query = "insert into mytable (myfield) values ('" . date('c') . "')";
Which will result in a query like:
insert into mytable (myfield) values ('2013-06-03T22:20:32+02:00')
This is an unambigious notation and should always work (Y-m-d will work fine too, as per your question, it only stores a date without any time). When using any other notation there's always the problem for the RDBMS that it has to know wether it has to interpret 02/12/1977 as February 12th 1977 or December 2nd 1977. Also, make sure that myfield (in my example) is of type DateTime or Date and not varchar and that you correctly escape reserved words like date in querystrings:
select foo, bar, `date`, foobar from mytable....
However, MySQL seems to 'allow' date (because of "MySQL permits some keywords to be used as unquoted identifiers because many people previously used them." wich is a stupid reason). It's best to just stick to escaping always:
select `foo`, `bar`, `date`, `foobar` from `mytable` ....
Please note that I did not use any sort of MySQLi or PDO prepared statements in this example; you should go read up on SQL injection and then on those topics and then go back to your code.
You can use the php class Date and use his format function
I am trying to compare two sets of times in order to find out if they're overlapping. Here is what I have at the moment..
$sql = "SELECT * FROM schedule WHERE starttime>='$starttime' AND endtime<='$endtime' AND day='$updateday'";
Now this doesn't work as it appears you cant compare time values...so I am completely unsure how this can be done?
Datetime fields in MySQL are stored as (for example)
'2011-05-03 17:01:00'
so you should be able to do something like
$starttime = date('Y-m-d H:i:s', $timestamp);
where $timestamp is a timestamp of the time you are concerned about. Then continue with your query.
You can make timestamps by using mktime() or strtotime() (if starting from a string representation of a time, like from an earlier MySQL query), or just time() for the current time.
I understand that you are using "time" for your datatype. This shouldn't be a problem, since you CAN compare fields using the "time" type. You might want to set your error reporting level to maximum or output your $sql statment just before mysql_query to doublecheck that you are constructing query which can return results at first place. Also check that you have valid dataset for your query in database (has happend to me once while debugging).
Why don't you use use unix timestamp to compare?
$sql = "SELECT * FROM schedule WHERE UNIX_TIMESTAMP(starttime)>=$starttime AND UNIX_TIMESTAMP(endtime)<=$endtime AND day='$updateday'";
Also I think you're comparing strings, which I'm not sure if it would work.
Assuming that you're using the TIME type, your format of "10:00:00" should work.
Not to sound like your mother, but be sure to parameterize your query after you get it working.
I did run the SELECT statement on the phpmyadmin on the sql before trying to do it on the webpage and was great, the thing is to use it and be thinking in this before:
CAST('the_value_you_want_to_be_compared', AS the_type_you_want_to_compare)
example:
If you want to compare the date of a day and your table name is activities:
SELECT * FROM activities WHERE date = CAST('2015-10-29', AS date)
and so on...
I'll explain my goal first: I want the user to query the database, and return rows only if those rows have been updated since their last query. No sense returning data they'd already have. So I created a column called 'lastupdated', a timestamp type which autoupdates every time any content in the row is updated. This works fine. Now, I want to form the query correctly. The user will have their previous query's timestamp saved, and via php will use it to compare their previous query's time with the time each row has been updated. If the row was updated after their last query, the row should be returned.
I made something like this,
SELECT * FROM users WHERE '2011-02-26 01:50:30' <= lastupdated
but its obviously much too simple. I checked the MySQL manual and found this page MySQL Time/Date Page. I'm sure the answer is here, but I've read through it any nothing really makes sense. I have a timestamp in the same format used by the MySQL timestamp type, but I don't know how I will compare them. Thank you very much for your help.
That query is exactly how you'd do it. As long as a stringified date-time is in MySQL's preferred format (yyyy-mm-dd hh:mm:ss), then it will be internally converted into a datetime value, and the comparisons will go ahead.
You'd only need the date/time functions you found if you want to do something more complicated than simple "greater/less than/equal" type comparison, e.g. "any records that have a December timestamp".
As Marc said, your code should work. But you probably want to do this programmatically with a variable for the time instead of the literal.
If you don't have the date-time specified as a string, but rather as a timestamp (e.g. from using the php time() function), then you can use the following query:
$query = "SELECT * FROM users WHERE FROM_UNIXTIME(" . $timestamp . ") <= lastupdated";
The key is the FROM_UNIXTIME() MySQL function.
I'm trying to insert a date ("This is a string") into a postgres database field. I'm getting the following error
ERROR: invalid input syntax for type timestamp: ""
Here is my code
$date = '2002-03-11';
$query = 'INSERT INTO dates(date) VALUES('.$pdo->quote($date).')';
$pdo->query($date);
I have absolutely no idea on how to do this?
You're trying to insert into a timestamp. You need to concatenate the time with the date. From the Postgres documentation:
Valid input for the time stamp types
consists of a concatenation of a date
and a time, followed by an optional
time zone, followed by an optional AD
or BC. (Alternatively, AD/BC can
appear before the time zone, but this
is not the preferred ordering.) Thus
1999-01-08 04:05:06
and
1999-01-08 04:05:06 -8:00
are valid
values, which follow the ISO 8601
standard.
Do:
$date = '2002-03-11 12:01AM';
I'm not sure why you're getting that error, with the value in the quotes empty like that. PostgreSQL certainly accepts dates without times into timestamp fields just fine. They default to a time of "00:00:00", the start of that day.
CREATE TABLE dates("date" timestamp);
INSERT INTO dates (date) VALUES ('2002-03-11');
SELECT * from dates;
date
---------------------
2002-03-11 00:00:00
There are a couple of things you're doing here that aren't quite right though, and one of them might improve your situation:
Using 'quote' instead of prepared statements in a real application is a first step toward allowing SQL injection attacks into your code, that's a bad habit to get into. The fact that you're getting an error here makes me wonder if PDO is doing something wrong in the middle here, which would be less likely to happen if you prepared the statement and passed the value more directly through.
You really should cast this directly from string to timestamp rather than depend on the implicit casting here. Example in straight SQL:
INSERT INTO dates (date) VALUES (cast('2002-03-11' as timestamp));
'date' is a SQL reserved word. You shouldn't name fields like that, because you can end up needing to wrap references to the name in quotes for them to be parsed correctly.
Your error seems to clearly state what the problem is:
ERROR: invalid input syntax for type timestamp: ""
It appears your query is trying to insert an empty string into a PostgreSQL field that has a type of 'timestamp'. If you were inserting an invalid string of some sort, it should appear in the error that you are recieving like:
ERROR: invalid input syntax for type timestamp: "foobardtimestamp"
Or, in your case, if your expected string was being passed, your error may look like this:
ERROR: invalid input syntax for type timestamp: "2002-03-11"
...but the error doesn't say that which makes me suspect your string isn't actually getting passed to the query like you think. The fact is, as previously pointed out: PostgreSQL should be perfectly capable of handling 2002-03-11 as a valid timestamp string.
PostgreSQL doesn't like inserting '' (empty string) as a timestamp and will complain with the error that you provided.
If you want to provide an empty string, you need to be sure you don't have a NOT NULL constraint on the column, and you need to use null instead of an empty string. If you aren't meaning to send an empty string, I would check on the value of $pdo->quote($date) to make sure you're getting the string that you want returned from that.
You can also try to output your generated SQL before you actually run the query to make sure it looks correct. I have a feeling, if you do, it will look something like this:
INSERT INTO dates(date) VALUES('')
Also, for what it's worth, your example says you're running:
$pdo->query($date); when I'm fairly certain you want: $pdo->query($query);