2

I was wondering how can I do the following.

Let's assume a user makes a comment in the provided comment box for an article let's say. I want to store the user comment into MySQL DB using a varchar(size) type. If I create the table with the varchar(100) and the user comment is longer than 100 chars, how can I adapt to these situations?

Because I would like to not limit its comment size (considering that is decent size). Would the solution be based on calculating the length of the comment prior to its insertion...? Assume PHP script is used to process the comment.

thank you

4

3 に答える 3

3

You can use Text data type for comments. But if you want to limit the user for some number of characters, you should consider limiting the input data in your HTML control (TextBox, input etc). Let the user know how many characters one can enter and set the max character size to the one set in the database against the comment field.

For example, you can use the maxlenght attribute on the input type in HTML

<input type="text" name="textboxname" maxlength="400" />
于 2013-01-11T04:34:20.400 に答える
1

Use text fields instead. varchar is limited to a max of 64k characters as of 5.0.3+. text can go quite a bit higher.

There's no point in calculating the size of a comment beforehand, because you'd have to do an alter table BEFORE you insert that long comment if the current field size is too small. Not a big deal with a small/few records table. But as a table grows, alter becomes a MAJOR operation, and will kill your server while the table's modified. You do NOT alter a table's layout on what amounts to a whim.

use text, and you can insert any amount of text from 0 to n bytes, where n's the max allowed by the particular text type you select.

于 2013-01-11T04:34:40.730 に答える
0

Unless you want to dynamically run alter table SQL commands (bad idea) you cannot adapt in this way. If you want to restrict users to the size of a varchar column then you should set your form input to enforce that restriction.

A better idea would be to use one of the TEXT datatypes. There will still be a size restriction but it will be larger, far past the 255 maximum available to varchars. Data above the maximum allowed size gets truncated. Retrieval of TEXT values can be slower than varchar, but isn't necessarily.

Another thing you could do is split the comments that are over the maximum size and store each piece as a row. You would then need to reassemble the pieces to provide the full comment. This would get away from any size issues, require the most programming and probably be the slowest.

于 2013-01-11T04:36:02.507 に答える