“if”正在运行或“else”正在运行

时间:2017-06-23 07:24:39

标签: php

我想制作用户身份验证脚本。如果用户想要注册,他/她将必须填写注册表单并单击“注册”

PHP

<?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\n";
}
if (!$selectdb = mysql_select_db("login",$con))
{
echo "database selection unsuccessful\n";
}
$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))
{

如果字段数大于0,则表示用户名已存在于数据库中,ELSE将数据添加到数据库中。我的问题是,ELSE条件不起作用,IF正在工作。我甚至尝试过使用ISSET,但仍然没有运气。

$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);
?>

2 个答案:

答案 0 :(得分:0)

您的else声明附近有1个额外的花括号。

以下是您的代码的清理版本:

if ($pwd == $confpwd){
    if (!$con = @mysql_connect("localhost", "root","","login")){
        echo "connection unsuccessful\n";
    }
    if (!$selectdb = mysql_select_db("login",$con)){
        echo "database selection unsuccessful\n";
    }
    $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);

我没有测试过它,也不想这样做,因为你真的需要使用mysqli()PDO(),你绝对应该验证用户输入。

答案 1 :(得分:0)

我猜你编写查询的方式也是错误的。您正在使用字符串变量,因此请按照以下格式编写查询。

$sql = "SELECT userName FROM userdetails WHERE userName='".$usrnm."'";

$sql2 = "INSERT INTO userdetails (userName, Password,mailID, firstName, lastName) VALUES('".$usrnm."','".$pwd."','".$email."','".$firstName."','".$lastName."')";

并且你在else语句之后使用了额外的结束括号。请删除它。