0

我正在尝试为我的网站制作用户系统,但在提交时遇到了一些问题。它总是向数据库提交 0 的所有内容。我在 w3schools 上阅读了有关全局和局部变量的信息,我认为这可能是我的问题,但我不确定。这是我的代码

<?php
$con = mysql_connect(localhost, 262096, 9201999);
if (!$con)
    {
    die('Could not connect: ' . mysql_error());
    }
mysql_select_db("262096", $con);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconf = $_POST['passwordconf'];
$email = $_POST['email'];
$securityq = $_POST['securityq'];
$qanswer = $_POST['qanswer'];

if(!isset($firstname) || !isset($lastname) || !isset($username) || !isset($password) || !isset($passwordconf) || !isset($email) || !isset($securityq) || !isset($qanswer))
    {
    echo "You did not fill out the required fields.";
    }

$uname = "SELECT * FROM users WHERE username='{$username}'";
$unamequery = mysql_query($uname) or die(mysql_error());
if(mysql_num_rows($unamequery) > 0) 
    {
    echo "The username you entered is already taken";
    }

$emailfind = "SELECT * FROM users WHERE email='{$email}'";
$emailquery = mysql_query($emailfind) or die(mysql_error());
if(mysql_num_rows($emailquery) > 0)
    {
    echo "The email you entered is already registered";
    }

if($password != $passwordconf)
    {
    echo "The passwords you entered do not match";
    }

$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*@([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
    {
    echo "The email you entered is not in name@domain format";
    }

else
    {
    $salt = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
    $hpassword = crypt($password,$salt);
    $insert = "INSERT INTO users (firstname, lastname, username, password, email, securityq, qanswer, salt)
    VALUES ('$firstname','$lastname','$username','$hpassword','$email','$securityq','$qanswer','$salt')";
    mysql_query($insert);


    if(!mysql_query($insert))
        {
        die('Could not submit');
        }
    else
        {
        echo "Information was submited.  Please check your email for confirmation";
        }
    }


?>
4

1 回答 1

0

让我试着回答。

首先,我同意转向 PDO 的建议。mysql_* 函数已弃用。但是,如果您想使用它,请直接sql 之前转义每个变量,因为' -symbols 在您的 sql 中:

$hpassword  = mysql_real_escape_string($hpassword );

至于我,下面的语法比 insert ... values() 更容易查看:

$insert = "INSERT INTO `users` 
    SET `firstname` = '$firstname',
    SET `hpassword` = '$hpassword'..."

实际上,我正试图忘记这种代码。我对简单的应用程序使用 PDO 或舒适的 uniDB 类。

无论密码匹配等错误如何插入用户都是正确的行为吗?你应该修复条件。

你的条件逻辑是错误的。你提交后if(!preg_match($regex, $email))。因此,如果电子邮件是正确的,它会提交。使用 ELSEIF 将其修复如下

$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*@([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";

if(mysql_num_rows($emailquery) > 0){
    echo "The email you entered is already registered";
}elseif($password != $passwordconf){
    echo "The passwords you entered do not match";
}elseif(!preg_match($regex, $email))
{
    echo "The email you entered is not in name@domain format";
}else{
    // insertion code HERE
}
于 2013-01-26T06:31:53.193 回答