如何设置 mysql 表以与 UPDATE WHERE 语句一起使用
我有一个存储用户信息的表。每个用户都有一个唯一的用户 ID,但其余信息各不相同。
当我尝试运行一条语句来更新该表时,其中 userid = $userid,我得到一个键“userid”的重复条目“XXX”
,其中 XXX 是他们的用户 ID。
我将 userid 字段设置为唯一,但显然我在某处做错了。
这是我的声明
UPDATE `users` SET `screenname` = '$screenname' ,`real_name` = '$real_name' ,`profimg` = '$profimg' WHERE `userid` = '$userid'
表结构
CREATE TABLE `users` (
`userid` int(11) NOT NULL,
`screenname` text COLLATE utf8_unicode_ci NOT NULL,
`real_name` text COLLATE utf8_unicode_ci NOT NULL,
`profimg` text COLLATE utf8_unicode_ci NOT NULL,
UNIQUE KEY `userid` (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
I have a table that i store userinfo. Each user has a unique userid, but the rest of their information varies.
When i try to run a statement to UPDATE that table, where userid = $userid, i get a Duplicate entry 'XXX' for key 'userid'
where XXX is their userid.
I have the userid field set as unique, but obviously ive done something wrong somewhere.
Here is my statement
UPDATE `users` SET `screenname` = '$screenname' ,`real_name` = '$real_name' ,`profimg` = '$profimg' WHERE `userid` = '$userid'
Table Structure
CREATE TABLE `users` (
`userid` int(11) NOT NULL,
`screenname` text COLLATE utf8_unicode_ci NOT NULL,
`real_name` text COLLATE utf8_unicode_ci NOT NULL,
`profimg` text COLLATE utf8_unicode_ci NOT NULL,
UNIQUE KEY `userid` (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您应该使用主键索引而不是唯一索引。主键索引禁用空条目,尽管您将列设置为 NOT NULL,但最好使用 PK 索引,因为列实际上是表的主键。
尝试像这样重新定义您的表:
您还可以查看 AUTO_INCRMENT 列属性。
还要确保在将变量放入查询中之前对其进行转义以否定 sql 注入...
First of all you should use a primary key index instead of a unique index. A primarey key index disables null entries, and although you set the collumn to NOT NULL it's better to use a PK index, since the collumn is in fact the primary key for the table.
try redefining your table like this:
You could also have a look at the AUTO_INCREMENT collumn attribute.
Also be sure to escape your variables before putting them into your query to negate sql injections...
我认为你正在使用 PHP。您是否将查询放在双引号中,就像
您使用单引号一样 PHP 不会替换您的变量
I think you are using PHP. did you put query in double quotes like
if you used single quote PHP won't replace your variables