I have integer fields in a table. The POSTs are sent by a complicated JavaScript. They send empty strings like "" but as you guessed MySQL doesn't allow empty strings in integer fields. Are there any options to allow empty strings? Like if it takes an empty string it will save it as NULL.
There are 2 ways to do this.
For Current Mysql Session (Temporary Solution)
First execute query to get current SQL mode of your mysql server.
mysql> SELECT ##sql_mode;
+----------------------------------------------------------------+
| ##sql_mode |
+----------------------------------------------------------------+
|STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------------------------+
1 row in set (0.00 sec)
If result contains STRICT_TRANS_TABLES, you have to remove that value to allow insert query to pass NULL value. Make sure your mysql User have privileges to apply this changes and restart Mysql Server after applying this.
SET GLOBAL sql_mode = '';
For Life Time of Mysql (Permanent Solution)
You have to update my.cnf file. Location of that file is : \etc\my.cnf or \etc\mysql\mysql.cnf
There will be some default parameters set under [mysqld] like
[mysqld]
innodb_file_per_table=1
default-storage-engine=MyISAM
performance-schema=0
max_allowed_packet=268435456
open_files_limit=10000
Just add one line under that
sql-mode=""
Make sure to restart Mysql Server after changing this file. Normally root user will be the owner of file so you have to login with root user on server.
For more details to understand what this SQL mode do.
STRICT_TRANS_TABLES
Enable strict SQL mode for transactional storage engines, and when possible for non-transactional storage engines. For details, see Strict SQL Mode.
Refer : http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_strict_trans_tables
NO_AUTO_CREATE_USER
Prevent the GRANT statement from automatically creating new user accounts if it would otherwise do so, unless authentication information is specified. The statement must specify a nonempty password using IDENTIFIED BY or an authentication plugin using IDENTIFIED WITH.
Refer: http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_auto_create_user
NO_ENGINE_SUBSTITUTION
Control automatic substitution of the default storage engine when a statement such as CREATE TABLE or ALTER TABLE specifies a storage engine that is disabled or not compiled in.
Refer : http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_no_engine_substitution
Removing sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" from my.ini has solved the issue.
Edit: Removing the line above works but it is a bad idea. It allows to have things like 0000-00-00 or empty string dates. Better keep the line above and don't insert empty sting into an integer field, instead convert empty string into NULL and then insert that NULL into integer field.
Assuming that the column allows for NULL values, you must explicitly tell MySQL to use a value of NULL, rather than passing an empty string (which is cast to 0):
INSERT INTO table (column_name) VALUES (NULL);
Related
What do these options mean, and what are the possible choices when creating the database?
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
#------------------------------------------------------------
# Script MySQL.
#------------------------------------------------------------
DROP DATABASE if exists BASETEST;
CREATE DATABASE IF NOT EXISTS BASETEST DEFAULT CHARACTER SET UTF8 COLLATE UTF8_GENERAL_CI;
USE BASETEST;
SET set's one of MySQL variables. Some of them are system variables some of them are user variables ...
SET SQL_MODE:
SQL_MODE is a system variables and you can see all possible modes in the documentation.
NO_AUTO_VALUE_ON_ZERO :
NO_AUTO_VALUE_ON_ZERO affects handling of AUTO_INCREMENT columns. Normally, you generate the next sequence number for the column by inserting either NULL or 0 into it. NO_AUTO_VALUE_ON_ZERO suppresses this behavior for 0 so that only NULL generates the next sequence number.
SET time_zone :
SET time_zone = "+00:00" Sets the session timezone on UTC.
Read more : How do I set the time zone of MySQL?
The SET statement is used here:
to assign values to variables that affect the operation of the server or clients
Neither the statement nor the variables are specific to database creation. In fact I don't think they should have any noticeable effect:
You cannot configure AUTO_INCREMENT handling in a per database basis (only per server or per session).
A database does not have a time zone (the server or current session do).
It's common though that tools that generate SQL dumps set some variables to configure session and get a predictable environment to run commands. Such variables tend to come from a template and aren't customised for script content.
Why does mysql accepts null data when updating a not null column and then converts the data to 0.
I am expecting an error it just does not show up. How can I get an error if someone tries to update a not null column to null? I need it so I can rollback the transaction if I get an error.Is there any configuration needed within the database to do this? Thank you
You've not specified which version of Mysql you're using, and in which mode. I'll answer this assuming you're running Mysql 5.7 without strict mode.
Strict mode controls how MySQL handles invalid or missing values in data-change statements such as INSERT or UPDATE. A value can be invalid for several reasons. For example, it might have the wrong data type for the column, or it might be out of range. A value is missing when a new row to be inserted does not contain a value for a non-NULL column that has no explicit DEFAULT clause in its definition. (For a NULL column, NULL is inserted if the value is missing.) Strict mode also affects DDL statements such as CREATE TABLE.
If strict mode is not in effect, MySQL inserts adjusted values for invalid or missing values and produces warnings (see Section 13.7.5.40, “SHOW WARNINGS Syntax”). In strict mode, you can produce this behavior by using INSERT IGNORE or UPDATE IGNORE.
Source: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-full
I recommend you to enable strict mode (STRICT_ALL_TABLES) and fix your application to support it; this will also enforce other query limitations where people are most commonly hit by ONLY_FULL_GROUP_BY.
To set the SQL mode at server startup, use the --sql-mode="modes" option on the command line, or sql-mode="modes" in an option file such as my.cnf (Unix operating systems) or my.ini (Windows). modes is a list of different modes separated by commas. To clear the SQL mode explicitly, set it to an empty string using --sql-mode="" on the command line, or sql-mode="" in an option file.
To change the SQL mode at runtime, set the global or session sql_mode system variable using a SET statement:
SET GLOBAL sql_mode = 'modes';
SET SESSION sql_mode = 'modes';
Source: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-setting
Why does mysql accepts null data when updating a not null column and
then converts the data to 0.
You question is not clear as we need the DDL of the table and the update , but as from what you are saying, Well logically because the column not null has a default value 0. check the below example.
create table Test_table ( name varchar(100) null , position_s varchar(100) default 'Y' not null)
SQL>
Table created
insert into Emp_table (name) values('Me')
SQL>
1 row inserted
SQL>
NAME POSITION_S
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
Me Y
#aaron0207 #Moudiz I am using laravel and updates data like this.
$specificReservation = Reservation::where('reference_id',$reference_id)->first();
$specificReservation->res_status = 1;
$specificReservation->payment_id = null;
$specificReservation->save();
I also tried to update manually in the database with this
UPDATE reservations SET payment_id = null
and it also shows no error so I think this is a database problem.
In MySQL I execute
insert into test (id, pw) values(1, password('1234'));
I got
Query OK, 1 row affected, 1 warning (0.01 sec)
I want to search a record by password, so I execute
select * from test where pw = password('1234');
I expect it to return one row, but I get an empty set. What did I do wrong?
The MySQL Password() function generates a nonbinary string currently (circa 2016) up to 41 characters. This is visible thru either calls to
SHOW CREATE TABLE mysql.user;
and examining the password column (which holds a hashed value):
`Password` char(41) ...
for, say, MySQL 5.6, or by hashing the same Cleartext value and lining it up to the output of the same SHOW CREATE TABLE on MySQL 5.7
`authentication_string` text ...
The hash values are consistent, yet in a different schema layout. Again, one in a VARCHAR(41), the other in a TEXT, as the same mysql_native_password PAM is being used. For now. Password() became deprecated as of 5.7.6 which means a new Plugin is in the works. Which they should be. They are plugins afterall.
What does it all mean? It means your schema needs to have a wide enough column to handle your use of Password() (note 5.7's switch to TEXT). And remember it is deprecated so keep an ear out for changes with MySQL hashing in the next few years.
I can find plenty of information on what strict mode does in MySql and MariaDB, but nothing on when to use it. This is common sense to a degree, but I would still like to have some general guidelines. For example, perhaps you:
Always use strict mode
Never use strict mode
Always use strict mode on tables that have financial data
etc
First, from MySQL documentation:
Strict mode controls how MySQL handles invalid or missing values in data-change statements such as INSERT or UPDATE. A value can be invalid for several reasons. For example, it might have the wrong data type for the column, or it might be out of range. A value is missing when a new row to be inserted does not contain a value for a non-NULL column that has no explicit DEFAULT clause in its definition. (For a NULL column, NULL is inserted if the value is missing.) Strict mode also affects DDL statements such as CREATE TABLE.
So, as #rick-james said: Always use strict mode. That is, until you get fed up with its restrictions. The mode is there to help you, but it may be painful.
Strict mode is also default on MariaDB since >10.2.3.
Get current mode: SHOW VARIABLES LIKE 'sql_mode';
Disable: mysql> SET sql_mode = '';
Enable: mysql> SET sql_mode = 'STRICT_ALL_TABLES'; (or STRICT_TRANS_TABLES).
For permanent change edit /etc/mysql/my.conf, [mysqld] section, sql_mode= variable.
I've created a table with some NOT NULL columns using phpMyAdmin.
CREATE TABLE `TEST` (`ID` INT PRIMARY KEY AUTO_INCREMENT,
`Firstname` VARCHAR(20) NOT NULL,
`Lastname` VARCHAR(20) NOT NULL)
There is no problem with INSERT operation. Database prevent to set a NULL field properly.
INSERT INTO `TEST`(`Firstname`, `Lastname`) VALUES ("Peter", null)
#1048 - Column 'Lastname' cannot be null
The accepted one is:
INSERT INTO `TEST`(`Firstname`, `Lastname`) VALUES ("Peter", "Smith")
1 row inserted.
Inserted row id: 1 (Query took 0.0004 sec)
But after I've created a record with non-NULL fields successfully, database allows me to UPDATE these fields to NULL.
UPDATE `TEST` SET `Lastname`=NULL WHERE `ID` = 1
1 row affected. (Query took 0.0006 sec)
I've tried "NULL" and 'NULL' as well, but database put them in the field as a string.
I'm really confused about this issue. Is this a phpMyAdmin bug or I'm doing something wrong?
You must not have SQL_MODE set to strict on your installation.
Issue
SET SQL_MODE='STRICT_ALL_TABLES'
or add
SQL_MODE='STRICT_ALL_TABLES'
under [mysqld] into your my.cnf
To find my.cnf, look in the MySQL config file C:\xampp\mysql\bin\my.ini.
At the top of that file are some comments:
# You can copy this file to
# C:/xampp/mysql/bin/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options (in this
# installation this directory is C:/xampp/mysql/data) or
# ~/.my.cnf to set user-specific options.
There it tells you where to find your my.cnf file.
Restart your mysql if necessary.
Maybe you have the rights to change the SQL mode via phpMyAdmin. Go the home (starting) page of phpMyAdmin, then click on Variables and enter "SQL mode" in the filter. Then you have access to some explanations via the question mark, and by clicking on this line you can edit the value of SQL mode and save it.
However this would be just for testing purposes, at the setting will revert to its original value once the server is restarted; hence the need to change the configuration file.