0

Recently i was searching for unique username registration using php.. I came across a piece of code which i am displaying below:

<?php 
$fname=trim($_POST['fname']);
$lname=trim($_POST['lname']);
$email=trim($_POST['email']);
$usn=trim($_POST['usn']);
$dept=trim($_POST['dept']);
$pass=trim($_POST['pass']);
$tel=trim($_POST['tel']);

$dbh = mysql_connect('localhost', 'root','') or die("<h3 style=\"color:red;\" align=\"center\">SERVER ERROR</h3>");
mysql_select_db('fy') or die("<h3 style=\"color:red;\" align=\"center\">SERVER ERROR</h3>");

$error= mysql_query("SELECT * FROM stud WHERE email='$email' OR usn='$usn' OR tel='$tel'") or die (mysql_error()); 

if (mysql_num_rows($error) > 0);
{
    die ("Sorry! Either email, usn or tel already exists!");
}

$query="INSERT INTO stud (fname, lname, email, tel, usn, dept, pass) VALUES ('$fname', '$lname', '$email', '$tel', '$usn', '$dept', '$pass')";
mysql_query($query);
$query="INSERT INTO log VALUES ('$usn','$pass',0,0)";
mysql_query($query);
print("REGISTERED");



 ?>
 <a href="login.php">LOGIN</a><br />

At this moment my database is completely empty. I've just created the database stud with the desired columns. Now the problem is when i try to register using my registration page, it gives me the error i specified in die that is

"Sorry! Either email, usn or tel already exists!"

How is this possible if there are no values in the database. In the registration form I've given

action="register.php" 

as a processing file. Also I've tried with mysql_fetch_assoc(), but i get the same error. Any help is appreciated. Thank you .

potashin
  • 44,205
  • 11
  • 83
  • 107
shet_tayyy
  • 5,366
  • 11
  • 44
  • 82
  • 1
    FYI, you are wide open to [SQL injections](http://stackoverflow.com/q/60174) – John Conde Apr 12 '14 at 15:40
  • You're using mysql, which is deprecated. You should use mysqli instead. –  Apr 12 '14 at 15:44
  • There really should be a Flag option for SQL Injectable code.. – Unix von Bash Apr 12 '14 at 15:47
  • Sorry i am new to php so i had no idea about it nor i am aware of mysqli.. But thanks for the suggestion.. Any link to learn about msqli would be really helpful.. And if its deprecated then what am i supposed to use?? Where can i learn about it more? – shet_tayyy Apr 13 '14 at 05:04

1 Answers1

1

Your first problem is that, as John Conde states, your code is vulnerable to SQL injection attacks.

Your second problem, and to answer your question, is probably because you have this:

if (mysql_num_rows($error) > 0);

instead of this:

if (mysql_num_rows($error) > 0)

Rhys
  • 1,439
  • 1
  • 11
  • 23