1
votes

AFAIK strings get truncated in MySQL when they are too long for VARCHAR column. I want to prevent this and would like to make sure that a string always gets properly saved. The problem is (from MySQL):

Values in VARCHAR columns are variable-length strings. The length can be specified as a value from 0 to 65,535. The effective maximum length of a VARCHAR is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.

The StringValidator checks for the max length with mb_strlen. So the byte length can be a different to that. But this length is the relevant one when the field is defined in the schema.

So how should I do it? Using the StringValidator solely is not appropriate, I think. So what would be the best way to ensure that nothing gets lost when I'd like to store strings in a certain, multi-byte encoding like UTF-8? Extending StringValidator? Use other mechanisms? Use 'strict' mode in sql? Or is there anything provided in Yii already?

/**
 * Class Item
 * 
 * @property string @str
 */
class Item extends ActiveRecord {
    public function rules() {
        return [
            [['str'], 'string', 'max' => 1000], // ????
        ];
    }
}
1

1 Answers

0
votes

Okay, found it out by myself: like it is also described here the length of the columns is encoding agnostic. I.e. if a column is defined with UTF8 then 3 bytes per character are reserved for this column (VARCHAR(1000) reserves 3000 bytes for the characters). So the validation will take the real length automatically into account. Now I hope that I'll never get problems with any kind of unicode string.