VARCHAR(4) 存储多于四个字符
我有一个 VARCHAR(4) 列,它从可能超过 4 个字符的输入接收数据。不过,这没关系,我让 MySQL 自然地(或者我是这么认为的)切断字符的结尾。
奇怪的是,当我稍后在 PHP 中查看数据库行结果(使用 PDO 驱动程序)时,会显示整个字符串,而不仅仅是 4 个字符。
奇怪的是,如果我在 MySQL CLI 上执行 SELECT 查询,它只返回 4 个字符。即使我执行 mysqldump,也只显示 4 个字符。
知道什么可能导致这种奇怪的不一致吗?
请注意,这些字符都是数字。
编辑:根据请求,这里有一些代表保存/获取方法的伪代码:
存储:
$data = array(
'name_first4' => $fields['num'],
// name_first4 is the column name with VARCHAR(4)
);
$where = $this->getTable()->getAdapter()->quoteInto('id = ?', $id);
$this->getTable()->update($data,$where);
获取,使用 Zend_Db_Table:
$row = $this->getTable()->fetchRow(
$this->getTable()->select()->where('id=?',$data)
);
I have a VARCHAR(4) column that receives data from an input that may be above 4 characters. This is okay, though, and I let MySQL naturally (or so I thought) cut off the end of the characters.
Strangely enough, when I'm looking at the database row results later in PHP (Using the PDO driver), the entire string is displaying, not just the 4 characters.
Weird thing is, if I do a SELECT query on the MySQL CLI, it only returns the 4 characters. Even when I do a mysqldump, only the 4 characters show.
Any idea what could cause this odd inconsistency?
Note that these characters are all numbers.
Edit: By request, here's some psuedocode that represents the save/fetch methods:
Storing:
$data = array(
'name_first4' => $fields['num'],
// name_first4 is the column name with VARCHAR(4)
);
$where = $this->getTable()->getAdapter()->quoteInto('id = ?', $id);
$this->getTable()->update($data,$where);
Fetching, using Zend_Db_Table:
$row = $this->getTable()->fetchRow(
$this->getTable()->select()->where('id=?',$data)
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您这样做:
$o
。'12345'
分配给相关属性/列。$o
并让 MySQL 将值截断为'1234'
。$o
中的属性/列并获取'12345'
。那么您就会看到让数据库默默地破坏数据的问题之一。
保存成功,您的对象不知道 MySQL 已截断数据,因此它保留
'12345'
而不是从数据库重新加载该列,并且您手上的数据不一致。如果您依赖 MySQL 默默地截断您的数据,那么您可能必须这样做:
我建议为您的对象添加严格的验证,以避免 MySQL 内部的静默截断。打开严格模式也会避免这个问题,但是您需要检查并加强所有错误处理和数据验证(这并不是一件坏事)。
If you're doing this:
$o
.'12345'
to the property/column in question.$o
and let MySQL truncate the value to'1234'
.$o
and get'12345'
back.then you're seeing one of the problems of letting your database silently mangle your data.
The save succeeds, your object has no idea that MySQL has truncated the data so it keeps the
'12345'
around rather than reloading that column from the database, and you have inconsistent data on your hands.If you're depending on MySQL silently truncating your data then you'll probably have to do this:
I'd recommend adding strict validations to your objects to avoid the silent truncation inside MySQL. Turning on strict mode would also avoid this problem but then you'd need to review and tighten up all your error handling and data validation (which wouldn't really be a bad thing).