MS Access: How does one insert NULL into DateTime field - php

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.

Related

T-SQL : How can I retrieve the OUTPUT from an INSERT statement with PEAR DB?

This is my first time using T-SQL
I am currently trying to get the last inserted ID from an INSERT statement in T-SQL using this query:
INSERT INTO TICKET( STATE, RECORD_DATE, ID_USER, TICKET_TYPE, TICKET_COM)
OUTPUT INSERTED.ID_TICKET AS lastId
VALUES ( 1, CONVERT(datetime, '24/02/2022 09:25:53'), 100, 1, 'It does not work')
As you've guessed, ID_TICKET is the identity, with auto_increment.
When I run this through MS SQL server management studio, I get the intended result : one row, with a unique lastId column containing the value of the last inserted id.
However on PHP, when I am running this using the query() method from PEAR database, I am running into some issue.
From reading the documentation, DB->query() will only return a resource in case of a SELECT query, while an INSERT query will just return a DB_OK type of answer: which is exactly what I am getting in PHP.
Hence my question : how can I retrieve the OUTPUT from an INSERT statement with PEAR DB?
I'd like to continue using PEAR, as I am adding functionality to an existing intranet heavily relying on it.
It is hosted on IIS 7 with SQL Server 9.0 using PHP 5.2.9 and PEAR DB 1.1.2.2.
Finally, I just did a simple INSERT by removing the OUTPUT INSERTED.ID_TICKET AS lastId line.
I then did a second query() call immediately after : SELECT ##IDENTITY as lastId and it now gives the desired results.
Pretty much what Álvaro González suggested.
Now, following Dan Guzman sugestion and adding SET NOCOUNT ON; at the beggining of my original INSERT with the OUTPUT clause indeed solved the problem !
I now get a result set with a unique row and column lastId as desired.
My hat off to both of you.

datetime field won't update in MySQL Database

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

how to use mysql update query and mysql insert query together?

this the condition: there is a form in html and php haivng around 120 fields its for a website i am making this form on submitting goes to a php page where i first retrive all the values using $_REQUEST[]and then using insert query insert all of them in their specific coloums in the same table in my mysql database. Now i will have to do all the process again for updating these values. Becuase syntax for insert query and update query are quite different .
I dont want to write another 100 lines of code . Is there any way to use the code i wrote inside my insert query to use to update the data.?
Actually in MySQL there is an alternative syntax for insert that is very similar to the syntax for update. You can write
insert customer set customerid=12345, firstname='Fred', lastname='Jones
etc.
Personally I prefer this syntax because it's easy to see what value is going into each field. This is especially true on records with long lists of fields.
On the minus side, it's not standard SQL, so if you ever decide to port your app to a different database engine, all your inserts would have to be rewritten.
Another option I've occasionally used is to write a little function to create your insert and update statements. Then the syntax of your function can be the same, no matter how different the generated code is.
Another alternative, and depending on requirements and keys, you could use:
replace into tbl (<cols>) values (<vals>)
which will insert if not exist, or replace based on keys (insert/update in one query)
or if you are only inserting and don't want to insert twice, you could use:
insert ignore into tbl (<cols>) values (<vals>)
where if the record is already inserted based on keys, it is gracefully ignored
for more info http://dev.mysql.com/doc/refman/5.0/en/replace.html
There is a quite similar syntax for INSERT and UPDATE:
INSERT INTO <table> SET
column1 = value1,
column2 = value2,
...
;
UPDATE <table> SET
column1 = value1,
column2 = value2,
...
WHERE <condition>
;
INSERT INTO yourtable (field1, field2, field3, ...)
VALUES ($field1, $field2, $field3, ...)
ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), etc...
Details on this construct here.

Can mssql_query detect inserting error?

I am trying to detect inserting result.
When I tried to insert with INSERT INTO table (1,2,'t') this will result in inserting error because of the third column of my table is decimal type,but mssql_query will return true.
but when I tested with INSET INTO table (1,2,'t') this will return false,like it should.
Why the first statement returning true? and how can we check that it is an error not true!!
Correct syntax is:
insert into table_name (column_name1, column_name2, ..)
VALUES (value_of_column1, value_of_column2, ..)
As you already know ordering part is not required, but i highly suggest you to do ordering first and then give values to it.
mysql_query return false on error and you can get error by using mysql_error function.
And keep this in your mind that you should surround values by quotations only when you are filling columns with type of varchar/char/date/datetime..
Other types like boolean, int, decimal and.. should be provided without quotations.
Hope it solve your problem ;)

Update a column in SQL, inserting a character at a specific point

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%'

Categories