Automatically trimming length of string submitted to MySQL

后端 未结 4 1747
南笙
南笙 2020-12-11 04:51

When I submit a form field to a mySQL database is there a way to set the database to automatically discard any data in excess of the data field length?

I know I can

相关标签:
4条回答
  • 2020-12-11 05:14

    MySQL by default does this already! It shouldn't in my view, but it does.

    If it is giving you error messages instead of just truncating the data, then perhaps traditional mode is on. Run SELECT @@SESSION.sql_mode and see what it says. If it spits out

    STRICT_TRANS_TABLES, STRICT_ALL_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER
    

    then it is in traditional mode; issue SET SESSION sql_mode='' every time you connect, or connect using an account with SUPER privileges and issue SET GLOBAL sql_mode='modes'.

    0 讨论(0)
  • 2020-12-11 05:28

    You mean you want to set this in a data definition script for example when creating a table? According to the documentation you can't do this. Perhaps you could use a trigger to handle data before it is inserted? Something like this (I can not garantuee that the code below actually works):

    CREATE TRIGGER chopdata BEFORE INSERT ON mytable
      FOR EACH ROW BEGIN
        NEW.myfield = SELECT SUBSTRING(NEW.myfield,1,20)
      END;
    

    Else you can chop out the maximum length by using substring straight in your query/procedure:

    SELECT SUBSTRING('your very long string goes here',1,20);
    
    0 讨论(0)
  • 2020-12-11 05:33

    Edit: This should not be the accepted answer.

    Incorrect answer: MySQL will truncate any insert value that exceeds the specified column width.

    This behavior should never be relied upon.

    0 讨论(0)
  • 2020-12-11 05:36

    Just set the DB field size to the max size you want to accept.
    if you want max 20 chars, then set it to varchar(20) or char(20).
    Just be careful with the utf8 inputs, some of them characters takes 2 places instead of one.
    But, as you can read in comments. Choosing a utf8 charset will solve this.

    If you are speaking about white spaces...Then usually you are suppose to use only one place in your code to do the insert/update/delete queries. In this place you can easily apply programmaticlly any filter you want, and be sure it will be applied to all of your inserts.

    0 讨论(0)
提交回复
热议问题