Reputation: 6308
// Check to see if p_name exists
$sql = mysql_query("SELECT patient_name FROM patient WHERE patient_name = '" . $p_name . "'");
if (mysql_num_rows($sql) == 0){
// patient database
mysql_query("INSERT INTO patient (patient_name)
VALUES ( '$p_name' )") or die (mysql_error());
}
else
die ("Patient name exist!");
Why does it still insert new record even if the patient_name exist in the database?
Is if (mysql_num_rows($sql) == 0)
correct?
Upvotes: 1
Views: 92
Reputation: 360682
The query probably failed for some reason. That means $sql
is a boolean FALSE. You try to pass that FALSE
to mysql_num_rows()
, which also fails, since it expects to get a result handle. That means mysql_num_rows() also returns a boolean FALSE
. In PHP, false == 0
is TRUE
, so you execute your insert statement.
NEVER assume a query has succeeded. ALWAYS check for failure. That means, as a bare minimum, you have:
$result = mysql_query(...) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
Upvotes: 1