php - preventing duplicate row data entries
问题描述
I had created a database which named student with ID, name, mat_number, specialty, age, and gender, in a PHP application.
I do not want the name or mat_number be taken in more than once.
I have done the connection to my database in a different page and called it in the add student page.
This following codes is for a faculty database collection
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender))
{
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}
else{
echo "Error: Complete all records";
}
}
?>
I want to get an error message demanding for a change if the 2 fields already exist in the database.
解决方案
如果记录已经存在,则要签入数据库的名字。
如果没有记录运行 sql insert 命令。
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
$sql = "SELECT * FROM `student` WHERE name = "'.$name.'" and UB_number = '".$matNo."'";
$conn->query($sql);
$cnt = $conn->rowCount();
if($cnt == 0){
$sql = "INSERT INTO `student`
(`name`, `UB_number`, `age`,`sex`, `specialty`)
VALUES
('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}else{
echo "Error: Complete all records";
}
}
推荐阅读
- ios - 支持 CocoaPod 和 Carthage
- javascript - this.state 在 .map 内为 0
- java - java.lang.NoClassDefFoundError: com.google.android.gms.common.internal.zzbo
- c - 如何水平移动星形图案?
- python - TypeError:在 Python2.7 中创建空字典时,'dict' 对象不可调用
- c# - 在 owin 中间件中读取响应体
- javascript - 我无法从 spotify 的 API 获取图像
- php - 如何在 PHP 中打印彩色字符串
- python - 将数据框中的列转换为“类”?
- bash - Bash:卷曲多行,将输出写入文件