1

我有一个要创建用户帐户的网站。该网站目前运行良好,但我想知道如何改进和解决我遇到的问题。如果站点将帖子发送到服务器端 php,它会正确创建用户,但是如果有人在没有发布的情况下加载服务器 php 文件,它将在数据库中创建一个所有值都为空的用户。我正在检查用户,但请帮我优化我的代码。先感谢您。

/// HTML ///

<form id="form_customer">
    // form stuff here, please note my button for submit is not in the form but outside
</form>

<button id="form_submit">Submit</button>
<button id="form_cancel">Cancel</button>

//Javascript jQuery

$("#form_cancel").click(function() {
  window.location = 'index.php';
});


$("#form_submit").click(function() {
$.post("incl/server_register.php", payload, function(data) {
    if(data == "500"){
        alert("An Error has occured.");
    }
    if(data == "200"){
        alert("Registration complete. Redirecting...");
        indow.location = 'index.php';
    }
    if(data == "400")
        alert("Username already exists. Please select another.");
},"json");

// And here is my server side PHP
$mysqli = new mysqli($dbHost, $dbUser, $dbPass);
$mysqli->select_db($dbDB);

// Check connection
if($mysqli->connect_error) {
    die('Connection Error: (' .$mysqli->connect_errno .') ' .$mysqli->connect_error);
}

if(isset($_POST))
{
    // Query DB 
$check = "SELECT * FROM table WHERE Username='$sUsername'";
$result = $mysqli->query($check);

if($result->num_rows == 0)
    {
        $query = "INSERT into table (blah blah)
        $result = $mysqli->query($query);
    if($result == false)
        echo json_encode("500");
    else {
        echo json_encode("200");
        mail($to, $subject, $message, $headers);
    }
}
else
    echo json_encode("400");
}
}
4

3 回答 3

2

检查用户名和密码是否不为空(也不要忘记修剪)。

if (!empty($_POST['username']&&!empty($_POST['password'])) {
     // Here create new account
}
于 2012-09-09T03:30:30.403 回答
1

isset($_POST)总是正确的。当页面加载而不发布时,$_POST设置为空数组。

改变是为了if (count($_POST) > 0)

于 2012-09-09T03:30:58.847 回答
1

你可以判断价值

$username = trim($_POST['username']);
$password = trim($_POST['password']);

if (!empty($username&&) && !empty($password)){

     //before you insert the data,you can do like this to avoid some special chars

     $username = strip_tags($username);

     //and then excute the sql to insert account
     //I suggest you use mysqli_query, while not mysql_query

}
于 2012-09-09T03:38:04.907 回答