How do I insert a current_timestamp into an SQL Server 2005 database datable with a timestamp column?
It should be simple but I cannot get it to work. Examples would be much appreciated.
if you can execute a query from PHP then it should just be a matter of using 'getdate()' ;
update MyTable set MyColumn=getdate();
or
insert into MyTable (MyColumn) values (getdate());
The column datatype should be datetime
You can either get the database to work out the date:
$sql = 'INSERT INTO tablename (fieldname) VALUES (getdate())';
or get PHP to work out the date
$sql = 'INSERT INTO tablename (fieldname) VALUES (\'' . date('Y-m-d H:i:s') . '\')';
then something like mssql_execute($sql); but this depends on how you are connecting to your database
To insert data into a timeStamp field, I think you have to use DEFAULT.
For example:
INSERT INTO User(username, EnterTS) VALUES ('user123', DEFAULT)
where EnterTS is a TimeStamp field
You just use the normal mechanism to execute your queries into SQL Server, and use what follows.
The current_timestamp function returns it
insert into table (creation_date) VALUES (current_timestamp)
Complete example
CREATE table timestamp_test (creation_timestamp datetime)
INSERT INTO timestamp_test (creation_timestamp) VALUES (current_timestamp)
SELECT * FROM timestamp_test
DROP TABLE timestamp_test
If you explain the error you are receiving (and post your insert or update code), it might make it easier to see what your problem is. One possible issue is that you must be inserting into a datetime field (or in 2008 you could use a date field as well). Occasionally people think that they can insert the current date into a timestamp field but even though the name of this data type seems as if it should be date related, this data type actaully has nothing to do with dates and times and cannot accept date data.
I realize this is an old post but I ran across this and figured others might too.
What I do is to create a field in the table using the datatype of datetime and then for the column properties for the default Value or binding, I enter getdate(). Every record that gets entered into the table now has a date and time stamp.
Related
Hi I am having an issue with updating a users last login time in my database, if I set it to update a different column it works perfectly, but it just does not work when i try to update the specific column "lastlogin".
My code:
#mysql_query("UPDATE my_users SET lastlogin=NOW() WHERE id=".$_SESSION["id"]);
My DB column:
column name: lastlogin
type: datetime
Null: No
Default: 0000-00-00 00:00:00
Anything wrong with the way the column is setup in the DB? Like I mentioned above if I was to tell it to put NOW() in another column it works fine.
Solved. There was another similar statement further down which was over riding this one! How stupid of me but easy to miss!
use mysql_error to try and find what is wrong, then post that into here so we can help if you need it. (Would comment but to low rep)
From my experience in the past, mysql_query() doesn't necessarily substitute variables before executing sql. Try writing in this format. Also use mysql_error to check if there are any issues with your code execution:
$sql = "UPDATE my_users SET lastlogin=NOW() WHERE id=".$_SESSION["id"];
mysql_query($sql) or die(mysql_error());
If there is no error, then there are few possibilities as to why the laslogin entry is not happening:
$_SESSION["id"] does not hold any value and no value is being passed to mysql.
There is no id matching with $_SESSION["id"].
To debug:
Also try updating some other columns.
You might also want to check if you are using correct extensions like PDO..
Also found that, earlier version of mysql doesn't support updating datetime column with now(). In that case try resetting column type to TIMESTAMP. Refer this for details: https://bugs.mysql.com/bug.php?id=27645
I have a php form with text fields, multiple choices and Date, Datetime, Time fields, i want to set the date, datetime and time fields to be optional while submitting the form. How to do so.? The values are inserted only Date, Date time, time field are entered.
Php code
// Fetching variables
$checkout_date_input = $_POST['checkout_date_input'];
$checkout_time_input = $_POST['checkout_time_input'];
$arrival_date_time = $_POST['arrival_date_time'];
$arrival_flightno = $_POST['arrival_flightno'];
$departure_date_time = $_POST['departure_date_time'];
$departure_flightno = $_POST['departure_flightno'];
//Insert Query of SQL
$query = mysql_query("insert into reservationform(booking_checkout_date, booking_checkout_time, booking_arrival_date, booking_arrival_flightno, booking_departure_date,booking_departure_flightno) values ('$checkout_date_input', '$checkout_time_input',
$arrival_flightno,'$departure_date_time',$departure_flightno)");
Solution #1
The best way is to check if the user has entered something, if they have you can pass the value, if they haven't you make the variable NULL.
if(!empty(trim($_POST['checkout_date_input']))){
$checkout_date_input = $_POST['checkout_date_input'];
} else {
$checkout_date_input = null;
}
Solution #2
Another thing that you can do is specify which column names you want to insert into the database.
INSERT INTO table (column1, column2) VALUES ('value1','value2')
This query will only insert values into column1 and column2, the other columns will be null.
If you set up a number of if statements, which check whether or not the field has been filled, you can determine which columns to insert values into and which not.
Both solutions are based on the assumption that your database columns allow null values, which will be inserted into the database.
Safety
Your code is very vulnerable for attacks to your database. I suggest using PDO and prepared statements to ensure the sanitation of your database queries. More info can be found here.
I am using a PDO prepared statement to insert values. One of the values is a date, and sometimes it can be empty. In MySQL schema, the date column is set to allow NULL values.
Let's assume date_column is a date and it allows NULL. When I do this:
$query = "INSERT INTO tbl(date_column) VALUES(?)";
$stmt = $pdo->prepare($query);
$stmt->execute(['']);
This is giving me this error:
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '' for column 'date_column' at row 1
In phpMyAdmin, I can execute this query without errors. It sets the date to 0000-00-00
INSERT INTO tbl(date_column) VALUES('')
Isn't that the same query that is executed by PDO behind the scenes in the code example above? What's wrong?
All I want is to be able to insert empty string '' as a date without errors. I don't care if it is set to 0000-00-00
This is too long for a comment.
This is a fundamental problem:
All I want is to be able to insert empty string '' as a date.
Strings are strings, and dates are dates. You should not want to insert an empty string into the column because that makes no sense. Instead, you should want to insert either a NULL value or the default value.
So, your code should look like:
INSERT INTO tbl(date_column)
VALUES(NULL)
or:
INSERT INTO tbl(date_column)
VALUES(DEFAULT)
The fact that MySQL does better type checking on prepared queries with parameters is actually a good thing.
Empty string is not a null... NULL is a NULL
$stmt->execute([null]);
I have a SQL table gathering form results. I noticed after about 200 results had been gathered, that instead of the date being in the format of 2011-06-01, that it was in the format of 2011-6-01, skipping the leading zero. This is giving some data processing problems. Is there a way to update all the 2011-6-xx values to make then 2011-06-xx? Solutions in either PHP/MySQL or just MS-SQL statements are acceptable, as the data is collected on a webserver using a PHP/MySQL form, exported to CSV, and then imported into an MS-SQL database on site for data analysis.
UPDATE `table` SET `date_column` = REPLACE(`date_column`, '2011-6-', '2011-06-') WHERE `date_column` LIKE '2011-6-%';
UPDATE Table1
SET field1 = REPLACE(field1, '2011-6-', '2011-06-')
WHERE field1 LIKE '2011-6%'
The where will allow you to use an index and replace much faster than looking through all rows.
Also in strict mode MySQL will not execute UPDATE statements without a where clause.
You talk about MS-SQL and MySQL. If it's MS SQL, then the below should work. I don't know if MySQL uses REPLACE or has an equivalent function.
UPDATE
Some_Table
SET
some_string = REPLACE(some_string, '2011-6-', '2011-06-')
WHERE
some_string LIKE '2011-6%'
I have an MS Access database (intolerably enough), and communicating with it through PHP (ODBC).
There is a DateTime field that I have to include in my INSERT statement. This field is NOT defined as "Required" in Access, meaning that it is indeed NULL-able, and in fact some of the rows in the Access database are already NULL.
The problem I'm having is simple: How to insert NULL through SQL? All the results I've found online have addressed it from something like Visual Basic or C#, whereas I'm using SQL through ODBC in PHP.
I have already tried the following:
INSERT INTO table_name (datetime_field) VALUES (NULL)
INSERT INTO table_name (datetime_field) VALUES (#NULL#)
INSERT INTO table_name (datetime_field) VALUES ('NULL')
INSERT INTO table_name (datetime_field) VALUES ('#NULL#')
INSERT INTO table_name (datetime_field) VALUES ('')
(There's about 30 other columns in my query.)
The exact error I get is 'Data type mismatch in criteria expression' when I try '' or NULL. The others return a parse error (understandably).
Please note that I have to include the field in the INSERT statement. The field has a default value, but in many cases the original data that I'm transporting has a NULL that must also be a NULL in the target database.
Thanks in advance!
Try the following. It works for me:
INSERT INTO sometable ( somedate, somethingelse )
SELECT Null AS Expr1, "foo" AS Expr2;
Basically, you are wrapping the null in the select query and letting SQL figure out how to represent it to the insert.
-- EDIT --
This SHOULD also work:
INSERT INTO sometable ( somedate, somethingelse )
values (Null , "foo");
But for some reason it doesn't with my default install.
On I hunch, I switched my DB from ANSI-89 to ANSI-92, and the VALUES method started working. I switched it back to ANSI-89, and it still works. Not only that, on ANY new database I create, it now also works. Weird... something in the installation must be getting changed, (and sticking) by the switching back and forth that's not just ANSI-89/92. This seems to be why we were getting different results.
You can switch the database ocwe by going to Office Logo->Access Options->OBJECT DESIGNERS->QUERY DESIGN. Change SQL Server Compatible Syntax (ANSI 92) - and checking "This database".
Ok, very odd.
I know you've already figured this out but there is also dbNull
INSERT INTO table_name (datetime_field) VALUES (DbNull.Value)
Try just leaving it blank
(values fld1,,fld2)
What are the libraries, you are using in order to talk to ODBC?
Could it be a problem with the syntax for null values, the way library interprets it?
See, if this page helps.
Note: I have not worked with PHP.
I have this type of error and
Try this.
INSERT INTO table_name (datetime_field) VALUES (DBNull.value)
It works fine for me.