Page 1 of 1

How to Code for already exist?

Posted: Fri Feb 05, 2010 10:41 pm
by adilmarwat2004
i have mysql table name "act",
contains fields (i)Roll#(primary) (ii)name (iii)marks

I want that when ever i enter the two same values in "Roll#" field and then submit the form from php, then i will show that Roll# already exist. how it is possible?

Please help?

Adil

Re: How to Code for already exist?

Posted: Sat Feb 06, 2010 12:48 am
by John Cartwright
Assuming your PK is a numerical ID.. the fastest way to perform the check is using COUNT(), and fetch the results.

Code: Select all

$sql = "
   SELECT COUNT(*) AS `numrows`
   FROM act 
   WHERE roll = ". (int)$roll ."
   LIMIT 1
";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
 
if ($row['numrows'] > 0) {
   //roll already exists
}