Reputation: 47
I have a form with more then 4 fields and all data inserted into those fields are related, so i want to achieve something different.
For example - I have 4 fields with names class
class_time
class_teacher
& batch_name
and each time i fill and submit the form the data will be submitted into database, basically it's a time-table script.
So if first time i added maths
12-01
ashok
IAS
these values and submitted the form and it got saved, now if second time i add same time and teacher name with different batch then it should show an error and form should not submit, because same teacher can not appear at two different classes at the same time. How could i achieve this with PHP.
Here are some code which i tried.
$sql2 = "SELECT * FROM `s_timetable`";
$res = mysql_query($sql2) or die(mysql_error());
$fetch_data = mysql_fetch_array($res);
if ($fetch_data['class_info'] && $fetch_data['teacher_info']) == $_POST['class'] && $_POST['teacher']
{
}
Upvotes: 2
Views: 2840
Reputation: 28
Simply add a query that will select class_time and class_teacher so that if it already exist you can produce an error msg.
$checksched = mysqli_query($con,"SELECT * FROM s_timetable WHERE class_time = '".$inputted_time."' and class_teacher = 'inputted_teacher' ")
$match = mysqli_num_rows($checksched);
if ($match > 0){
echo "<script>
alert('Teacher already exist!');
</script>";
}
Upvotes: 0
Reputation: 711
Instead of doing this in PHP you could just add a composite unique key that would not allow having the same teacher at the same time in the database.
ALTER TABLE s_timetable ADD CONSTRAINT myUniqueConstraint UNIQUE(class_time, class_teacher);
Now everytime you would try to insert new data it would return an SQL error if the same teacher is there at the same time.
Multiple column index documentation
Upvotes: 1
Reputation: 5501
You need to check first that user is already in the table or not.
$sql = mysql_query("select * from table_name where class_time ='" . $_REQUEST['class_time'] . "' AND class_teacher ='" . $_REQUEST['class_teacher'] . "'");
$record = mysql_num_row($sql);
if ($record) {
echo "Record already exits";
exit();
} else {
//insert query
}
Note : Stop using mysql
it is deprecated.
Upvotes: 1
Reputation: 2447
before inserting new data you can check the things by below given query and if that query return more than 0 rows you can show an error message
select * from `tablename` where `class_time` = '".$class_time."' and `class_teacher`='".$class_teacher."'
You shouldn't use any mysql_*-functions. They have been deprecated since php 5.5 and completely removed in latest php versions
Upvotes: 3