I have the following table in my database:
CREATE TABLE subjects (
subject_id int(11) NOT NULL AUTO_INCREMENT,
subject text,
PRIMARY KEY (subject_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1;
I also insert the table data from this PHP and it works fine:
<?php
include('Conexion.php');
$subject = "";
if (isset($_POST['reg_subject'])) {
$text = $_POST['text'];
$query = "INSERT INTO subjects (subject) VALUES('$text')";
mysqli_query($conn, $query);
header("Location: index.PHP");
}
?>
The problem is that the user can enter duplicate subjects and I would like to avoid that.
I have tried to show an alert message if the subject already exists, but it continues accepting duplicate subjects. How could I avoid duplicate subjects with the same name?
This is how I’m doing it:
<?php
include('Conexion.php');
$subject = "";
if (isset($_POST['reg_subject'])) {
$text = $_POST['text'];
$subject_check_query = "SELECT * FROM subjects WHERE subject='$subject'";
$result = mysqli_query($conn, $subject_check_query);
$text = mysqli_fetch_assoc($result);
$message = "Already Exists";
if ($text) { // if subject exists
if ($text['text'] === $subject) {
echo "<script type='text/javascript'>alert('$message');</script>";
}
}else{
$query = "INSERT INTO subjects (subject) VALUES('$text')";
mysqli_query($conn, $query);
header("Location: index.php");}
}
?>