SQL NULL insertion not working - mysql

I'm having some odd SQL problems when inserting new rows into a table. I have set some columns to NULL, as I have with another table in my database. Obviously when no data is passed through on insertion it should enter NULL into the record, however currently it is not.
I have checked all settings in comparison with my other table (which is inserting records as NULL correctly) but can't find the issue. The columns appear as below, in both tables.
`statement_1` varchar(255) DEFAULT NULL,
No data is being pasted through (so not a blank space issue). Can anyone suggest why one table is doing as expected but the other is not?
Using below as the insert statement
$statement_a = "INSERT INTO statements (ucsid, statement_1, statement_2, statement_3, statement_4, statement_5, statement_6, statement_7, statement_8, statement_9, statement_10) VALUES (:ucsid, :statement_1, :statement_2, :statement_3, :statement_4, :statement_5, :statement_6, :statement_7, :statement_8, :statement_9, :statement_10)";
$q_a = $this->db_connection->prepare($statement_a);
$q_a->execute(array(':ucsid'=>$ucsid,
':statement_1'=>$statement_1,
':statement_2'=>$statement_2,
':statement_3'=>$statement_3,
':statement_4'=>$statement_4,
':statement_5'=>$statement_5,
':statement_6'=>$statement_6,
':statement_7'=>$statement_7,
':statement_8'=>$statement_8,
':statement_9'=>$statement_9,
':statement_10'=>$statement_10));

I can not add comments as I am new:
Try a simple INSERT statement using NOT phpmyadmin. Try
http://www.heidisql.com/ OR https://www.mysql.com/products/workbench/
INSERT INTO statements (ucsid) VALUES (123)
INSERT INTO statements (ucsid, statement_1) VALUES (123, NULL)
In both cases the statement_1 should be NULL. Which in your case most likely is not. However that would tell the problem lies in the database table and NOT with php or the php execute method you are using.
Also is the statement_1 field defined as NOT NULL and the default set as NULL? which can not happen.
Try recreating a new database and a new table with no records and than try inserting NULL as values as a test.
Also can you post the SQL of your database and table with Character Set and Collation

I've fixed the issue by ensuring that NULL is passed through the functions if nothing has been inserted by using the following code
if($_POST['statement_1'] == '') { $statement_1 = NULL; } else { $statement_1 = $_POST['statement_1']; }

Here the value passed by the varriable $statement_1 will be ""
Try this query SELECT * FROM my_table WHERE statement_1 ="".You will get rows.
Which means you are assigning some values to $statement_1 else it should be null.
Check your code. Hope this helps

Related

MySQL ERROR 1265: Data truncated for column

I can't figure out why I'm getting this message. I'm using MySQL Workbench and am editing the values in an ENUM field that connects to a dropdown choice in my app.
Everything seems to be fine. I've searched on this error and all I find refers to datatype mismatches but, in this instance, that's not possible with ENUM when feeding it an array of string values.
Here's the SQL
Executing:
ALTER TABLE `mydbase`.`average_monthly_expenses`
CHANGE COLUMN `expense_category` `expense_category` ENUM('Home', 'Healthcare', 'Child care', 'Groceries and supplies', 'Eating out', 'Utilities', 'Telecomms', 'Laundry and cleaning', 'Clothes', 'Education', 'Entertainment gifts vacation', 'Auto and transportation', 'Insurance', 'Savings and investments', 'Charitable contributions', 'Itemized monthly payments') NULL DEFAULT NULL ;
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1265: Data truncated for column 'expense_category' at row 1
SQL Statement:
ALTER TABLE `mydbase`.`average_monthly_expenses`
CHANGE COLUMN `expense_category` `expense_category` ENUM('Home', 'Healthcare', 'Child care', 'Groceries and supplies', 'Eating out', 'Utilities', 'Telecomms', 'Laundry and cleaning', 'Clothes', 'Education', 'Entertainment gifts vacation', 'Auto and transportation', 'Insurance', 'Savings and investments', 'Charitable contributions', 'Itemized monthly payments') NULL DEFAULT NULL
Any suggestions are very welcome
The query itself is correct.
modelling fiddle
Execute
SELECT DISTINCT expense_category, HEX(expense_category)
FROM mydbase.average_monthly_expenses
and check the output for the values which are not listed in the column definition.
There may be typos, leading/trailing spaces or another non-printed symbols, double spaces in the middle of the value, or there may be some collation problems.
UPDATE
My current field definition I'm trying to change to the above is ENUM('Home', 'Living', 'Telecommunications', 'Transportation', 'Other'). When I run your suggested SQL I just get Housing and Other listed.
These values are absent in new column definition - so server cannot convert them and truncates the values.
Recommendations: alter column definition, add new values to ENUM values list but do not remove old ones; update table and replace old values with new ones; alter column definition and remove old values from the list.
#Akina
So I figured out why I was blocked from editing the values. It would not let me make any edits that changed either value "Housing" or "Other". I did as you suggested, adding my new values to the existing ones, no problem, that worked fine. I couldn't however delete "Housing" or "Other", but the other prior values deleted fine. For the moment, I kept both, using "Housing" instead of "Home" and leaving "Other" at the end.
But I wanted to know however why those two values were protected, and then it dawned on me, there were existing records using those values. I manually changed all instances using "Other" to "Telecomms" and then I could remove "Other" from the ENUM values. All good now.

Check for NULL or empty variable (MySQL stored procedure)

Can someone indicate the proper syntax to determine whether a variable is NULL or empty and then take appropriate action to set the variable depending on the result.
I currently have a test for NULL which works fine (part of a MySQL SELECT statement / stored procedure).
IFNULL(#previousTs, '2017-00-04 00:00:01') ts
I want to include (in the same single line) a test for empty (NULL or empty both results in #previousTs being set to 2017-00-04 00:00:01).
You can try like this:
IF(#previousTs IS NULL or #previousTs= '', '2017-00-04 00:00:01', #previousTs )

JSON_SET isn't updating null JSON field in MySQL

I have a nullable JSON MySQL 5.7 field which I am finding almost impossible to get working.
Example query:
UPDATE `json_test` SET `data` = JSON_SET(`data`, '$.a', 1)
If the field data is NULL already, it won't update.
If it's { "a" : 2 }, then it'll update correctly to 1. I need it to set if not set already, which is what JSON_SET is supposed to do.
Any ideas what's happening?
1) An alternative is to check for null and return an valid empty JSON set ({}) to JSON_SET in those situations, so it just puts in the new data.
UPDATE json_test SET data = JSON_SET(IFNULL(data,'{}' ), '$.a', 1)
2) Finally, another option would be for the data specification to have a default value of {}, ex.
`dataJson TEXT DEFAULT '{}',`
I prefer the first option I presented as I like leaving fields NULL until I need them to have data but then I expect them to start packing in the JSON data immediately!
Updating the entire table for that is an overkill and changing the table definition as well.
This should have no noticeable performance impact:
UPDATE `json_test` SET `data` = JSON_SET(COALESCE(`data`,'{}'), '$.a', 1)
Explanation:
JSON_SET needs a full processing of the column in any case, so it will be evaluated for validity, parsed, etc.
The COALESCE changes a NULL field to an empty JSON object, so the json will be valid and the SET will be successful.
You probably won't be able to measure a performance difference.
it's not supposed to work with nulls
Otherwise, a path/value pair for a nonexisting path in the document is
ignored and has no effect.
Now mysql doesn't let you use a subquery on the same table that's being updated, but you could probably stil solve this with an UPDATE JOIN using CASE/WHEN but I am too lazy so I leave you with a two query solution.
UPDATE `json_test` SET `data` = JSON_SET(`data`, '$.a', 1) WHERE data IS NOT NULL;
UPDATE `json_test` SET `data` = JSON_OBJECT('$.a', 1) WHERE data IS NULL;

How do you properly update a mysql field with NULL?

How does one properly update a mysql field with a NULL value when using a variable in the sql query?
I have a variable called $timestamp. When it's set to date( Y-m-d h:i:s ) I have to wrap it in quotes because I'm passing a string in my mysql query. When $timestamp is set to NULL, the database query contains '' as the value for $timestamp and the field updates to 0000-00-00 00:00:00. It's important to keep this field as NULL to show that the process has never been run before.
I don't want to use now() because then my sql statement is not in sync with my class variable $timestamp.
I don't want to set $timestamp to 'NULL' because then that variable is not accurate. It's no longer NULL, it's set to a string that contains the word NULL.
What am I missing here?
The correct SQL syntax to set a column to NULL is:
UPDATE Table SET Column = NULL WHERE . . .
(note the lack of quotes around the literal NULL).
Are you performing this UPDATE using SQL or using some kind of framework? If a framework, it should recognize NULL values and pass them to the database correctly for you.
After a lot of research, I've found that this is a well known problem with no good solution if you are writing your sql queries outright.
The correct solution is to use a database abstraction layer like PDO ( for PHP ), or Active Record ( used in frameworks like Codeignitor and Ruby on Rails ).

linq to sql string property from non-null column with default

I have a LINQ to SQL class "VoucherRecord" based on a simple table. One property "Note" is a string that represents an nvarchar(255) column, which is non-nullable and has a default value of empty string ('').
If I instantiate a VoucherRecord the initial value of the Note property is null. If I add it using a DataContext's InsertOnSubmit method, I get a SQL error message:
Cannot insert the value NULL into column 'Note', table 'foo.bar.tblVoucher'; column does not allow nulls. INSERT fails.
Why isn't the database default kicking in? What sort of query could bypass the default anyway? How do I view the generated sql for this action?
Thanks for your help!
If you omit the column, the value becomes the database default, but anything you insert is used instead of the default, example:
INSERT INTO MyTable (ID, VoucherRecord) Values(34, NULL) -- Null is used
INSERT INTO MyTable (ID) Values(34) -- Default is used
Picture for example you have a column that defaults to anything but NULL, but you specifically want NULL...for that to ever work, whatever value you specify MUST override the default, even in the case of NULL.
You need to set Auto-Sync to OnInsert, Auto Generated Value to true and Nullable to false for your column to work. See here for a full run-down with explanation on the Linq side.
For viewing the generated SQL, I have to recommend LinqPad