2012-09-09 143 views
1

我有一個網站用於創建用戶帳戶。該網站目前運作良好,但我想知道如何改善和解決我有問題。如果站點發送帖子到服務器端php,它會正確創建用戶,但是如果有人加載服務​​器php文件而沒有發佈,它將創建一個用戶到db中,所有值都爲空。我正在做一些檢查用戶,但請幫我優化我的代碼。先謝謝你。

/// 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"); 
} 
} 

回答

2

檢查用戶名和密碼是否爲空(也不要忘記修剪)。

if (!empty($_POST['username']&&!empty($_POST['password'])) { 
    // Here create new account 
} 
+0

哪來這去了?我檢查用戶後?或者它會取代我(如果(isset($ _ POST)))?以及我如何修剪? – Jareddlc

1

isset($_POST)總是如此。當頁面被加載而沒有發佈時,$_POST被設置爲一個空數組。

變化是if (count($_POST) > 0)

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 

} 
+0

謝謝你的建議! – Jareddlc