How to Code for already exist?

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
adilmarwat2004
Forum Commoner
Posts: 44
Joined: Fri Sep 04, 2009 11:28 pm

How to Code for already exist?

Post 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
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: How to Code for already exist?

Post 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
}
Post Reply