I want to make a user authentication script. Here if the user wants to sign up, he/she will have to fill the registration form and click "Sign up"
<?php
$usrnm=$_POST["userName"];
$email=$_POST["mailID"];
$pwd=$_POST["Password"];
$firstName=$_POST["firstName"];
$lastName=$_POST["lastName"];
$confpwd=$_POST["ConfirmPassword"];
if ($pwd == $confpwd)
{
if (!$con = @mysql_connect("localhost", "root","","login"))
{
echo "connection unsuccessful
";
}
if (!$selectdb = mysql_select_db("login",$con))
{
echo "database selection unsuccessful
";
}
$sql = "SELECT userName FROM userdetails WHERE userName='$usrnm'";
$sql2 = "INSERT INTO userdetails (userName, Password,mailID, firstName,
lastName) VALUES ('$usrnm','$pwd','$email','$firstName','$lastName')";
$retval = mysql_query( $sql, $con );
while($row = mysql_fetch_row($retval))
{
If the number of fields is more than 0, this means that the Username is already present in the database and ELSE add the information the database. My problem is, the ELSE condition is not working and IF is working. I even tried using ISSET but still no luck.
$fields=mysql_num_fields($retval);
if ($fields>0)
{echo "Username already exists";}
else
{$retval2 = mysql_query( $sql2, $con );
echo "Information added";
}
}
}
}
else
{
echo "Opps...";
}
mysql_close($con);
?>
You had 1 extra curly bracket close to your else
statement.
Here's a cleaned up version of your code:
if ($pwd == $confpwd){
if (!$con = @mysql_connect("localhost", "root","","login")){
echo "connection unsuccessful
";
}
if (!$selectdb = mysql_select_db("login",$con)){
echo "database selection unsuccessful
";
}
$sql = "SELECT userName FROM userdetails WHERE userName='$usrnm'";
$sql2 = "INSERT INTO userdetails (userName, Password,mailID, firstName, lastName) VALUES ('$usrnm','$pwd','$email','$firstName','$lastName')";
$retval = mysql_query( $sql, $con );
while($row = mysql_fetch_row($retval)){
$fields=mysql_num_fields($retval);
if ($fields>0){
echo "Username already exists";
} else {
$retval2 = mysql_query( $sql2, $con );
echo "Information added";
}
}
} else {
echo "Opps...";
}
mysql_close($con);
I haven't tested it nor do I want to do that, because you seriously need to use either mysqli()
or PDO()
and you should definitely validate the user inputs.
I guess the way you written the queries is also wrong. You are using string varaibles so follow the below format to write queries.
$sql = "SELECT userName FROM userdetails WHERE userName='".$usrnm."'";
$sql2 = "INSERT INTO userdetails (userName, Password,mailID, firstName, lastName) VALUES('".$usrnm."','".$pwd."','".$email."','".$firstName."','".$lastName."')";
and also you have used an extra closing bracket after else statement. Please remove that.