php 如何解决 SQLSTATE[23000]:完整性约束违规:1062 重复条目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11349426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to solve SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry?
提问by Milad R
This is my MySQL error.
这是我的 MySQL 错误。
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 2
I googled it and read something about it, bud I couldn't understand.
我用谷歌搜索并阅读了一些关于它的内容,但我无法理解。
How to solve it?
如何解决?
This is the main piece of addStudent.php:
这是主要部分addStudent.php:
require_once('../db.php');
$db = new DB();
if (isset($_POST['st_fname']) && isset($_POST['st_lname']) && isset($_POST['st_class']) && isset($_POST['st_grade']))
{
$db->addStudent($_POST["st_fname"], $_POST["st_lname"], $_POST["st_class"], $_POST["st_grade"], $_POST["checkOlamp"]);
}
and this is a part of db.php:
这是以下内容的一部分db.php:
public function addStudent($fname, $lname, $classnum, $grade, $olamp)
{
$query = "INSERT INTO t_student (s_fname, s_lname, s_class, s_grade, s_olamp) VALUES('$fname', '$lname', '$classnum', '$grade', '$olamp');";
$this->execute($query);
}
And the t_student has a filed as primarykey which is auto increment.
并且 t_student 有一个字段作为primary键,它是自动递增的。
- db.php is something that I always use it instead of mysql_connection function in php, but I don't know what it is exactly. I know something that called "PDO" is used there.
- db.php 是我一直使用它而不是 php 中的 mysql_connection 函数的东西,但我不知道它到底是什么。我知道那里使用了一种叫做“PDO”的东西。
回答by Arnaud Le Blanc
It means that the values of some column in your table must be unique, and you are trying to insert a duplicate row.
这意味着表中某些列的值必须是唯一的,并且您正试图插入重复的行。
BTW, your function is vulnerable to SQL injection, you should always escape your data before including it in a SQL query.
顺便说一句,您的函数容易受到 SQL 注入的影响,您应该始终在将数据包含在 SQL 查询中之前对其进行转义。
回答by Ukasha
Another easy way to solve "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry" is to pass the values in the input fields of form like this: you can see value before placeholder... note:articles is the DB table name
解决“SQLSTATE[23000]: Integrity constraint conflict: 1062 Duplicate entry”的另一种简单方法是在表单的输入字段中传递值,如下所示:您可以在占位符之前看到值...注意:文章是数据库表名
<div class="form-group">
<label for="exampleInputTitle">Title</label>
<input type="title" name="title" class="form-control" id="exampleInputTitle"
aria-describedby="emailHelp"
value="<?php echo $articles->title;?>"placeholder="Enter title">
<small id="titleHelp" class="form-text text-muted"></small>
</div>

