Pittz Pittz - 3 months ago 12
PHP Question

SQL Query for checking a particular ID have same date or not

I want to execute a sql query so that it checks whether there is a unique date for a id, meaning- a particular id must not have same date.

$query = "SELECT PersonID FROM status WHERE Date='$Date' ";
$result = mysql_query($query);

$count = mysql_num_rows($result); // if email not found then register

if($count == 0){


if(mysql_query("INSERT INTO status(PersonID,FirstName,Status, Date) VALUES('$PersonID','$FirstName','$Status','$Date')"))
{
?>
<script>alert('successfully Added ');</script>
<?php
}
else
{
?>
<script>alert('error while registering you...');</script>
<?php
}
}

else{
?>
<script>alert('Sorry Attendence already taken ...');</script>
<?php
}

}


But with this query it does not allow another id to have same date. I want to filter only unique date for a particular id. Another id can have same date.

Answer

Your code doesn't work because your first query checks whether there is any record on the given date. Instead, you should check whether there is a record with the same PersonID on the given date.

Change:

SELECT PersonID FROM status WHERE Date='$Date'  

To:

SELECT PersonID FROM status WHERE Date='$Date' AND PersonID = '$PersonID'

You should also learn to use prepared statements and parameterized queries because inserting data you get from the client directly into your query is not secure.

Comments