I have following table attendance
+--------------------------------+
| rollno | sub | date | presenty |
+--------------------------------+
It currently do not have any row. I want to add unique row with same value of rollno
, sub
, date
and presenty
. If any new entry comes with the same credentials, then I want to show user an alert message. Else, new entry should be created. I have written the following code:
$rollno = $_POST['rollno'];
$subject = $_POST['subject'];
$date = $_POST['date'];
$presenty = $_POST['presenty'];
$date_tmp = date_create($date);
$date_new = date_format($date_tmp, "d-m-Y");
$q = $conn->prepare("SELECT COUNT(`presenty`) FROM `attendance` WHERE `rollno` = ? AND `sub`=? AND `date`=?");
$q->bind_param("sss",$rollno,$subject,$date);
$q->execute();
$q->bind_result($pres);
$q->fetch();
$rows= $q->num_rows;
$q->close();
if($rows == 0){
$insrtqry = $conn->prepare("INSERT INTO attendance(rollno, sub, date, presenty) VALUES(?,?,?,?)");
$insrtqry->bind_param("ssss",$rollno, $subject, $date_new, $presenty);
if($insrtqry->execute()){ ?>
echo "Record Inserted Successfully";
} else {
echo "Record not added";
}
} else {
echo "Record already exists";
}
But, even if the table has no entry in it, when I try to insert a new record, the count query returns 1 and the else part executes. What is the problem? please help.