Automatically clip strings to the proper length on insert

前端 未结 3 729
你的背包
你的背包 2021-01-15 16:35

I have a table with various VARCHAR fields in MySQL. I would like to insert some user data from a form via PHP. Obviously if I know the field lengths in PHP, I can limit the

3条回答
  •  盖世英雄少女心
    2021-01-15 17:01

    Actually, MySQL truncates strings to the column width by default. It generates a warning, but allows the insert.

    mysql> create table foo (str varchar(10));
    mysql> insert into foo values ('abcdefghijklmnopqrstuvwxyz');
    Query OK, 1 row affected, 1 warning (0.00 sec)
    mysql> show warnings;
    +---------+------+------------------------------------------+
    | Level   | Code | Message                                  |
    +---------+------+------------------------------------------+
    | Warning | 1265 | Data truncated for column 'str' at row 1 | 
    +---------+------+------------------------------------------+
    mysql> select * from foo;
    +------------+
    | str        |
    +------------+
    | abcdefghij | 
    +------------+
    

    If you set the strict SQL mode, it turns the warning into an error and rejects the insert.


    Re your comment: SQL mode is a MySQL Server configuration. It probably isn't PDO that's causing it, but on the other hand it's possible, because any client can set SQL mode for its session.

    You can retrieve the current global or session sql_mode value with the following statements:

    SELECT @@GLOBAL.sql_mode;
    SELECT @@SESSION.sql_mode;
    

    The default should be an empty string (no modes set). You can set SQL mode in your my.cnf file, with the --sql-mode option for mysqld, or using a SET statement.

    Update: MySQL 5.7 and later sets strict mode by default. See https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html

提交回复
热议问题