我需要在SQL数据库中防止重复的学号。我不知道在哪里插入php代码来做到这一点。
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['studnum']) && isset($_POST['password'])) {
$name = $_POST['name'];
$studnum = $_POST['studnum'];
$password = $_POST['password'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, studnum, password) VALUES('$name','$studname', '$password')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
else
{
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
答案 0 :(得分:2)
为您认为可以创建唯一记录的某些列添加唯一
$result = mysql_query("INSERT INTO products(name, studnum, password) VALUES('$name','$studname', '$password') ON DUPLICATE KEY UPDATE studnum=VALUES(studnum)");
它会更新记录并防止您显示重复错误。
答案 1 :(得分:0)
在db
中运行以下SQL语句alter table products add unique index(studnum);
这将告诉mySQL,studnum字段应该是唯一的,并且如果创建了副本,它将导致它给出错误消息。