2015-01-05 55 views
-2

我是PHP的初學者。在註冊中使用mysql_query()時出現不正確的返回

當我註冊一個新用戶時,當我使用mysql_query時,我收到了一個不合適的'return'(-1而不是1)。 不帶「mysql_query」返回的行是正確的。

我在做什麼錯?

public function register ($username, $password, $activationcode) { 
    $username = $this->parse($username); 
    $password = $this->parse($password); 

    $query_search = "SELECT * from tbl_user WHERE username = '".$username."' "; 
    $query_exec = mysql_query($query_search) or die(mysql_error()); 
    $no_of_rows = mysql_num_rows($query_exec); 

if ($no_of_rows == 0) 
{ 
     $newUser="INSERT INTO tbl_user(username, password,activationcode) VALUES ('".$username."', '".$password. "','".$activationcode."')"; 
     if(mysql_query($newUser)) 
     { 
     return 1; 
     } 
}else { 
    return -1; 
    } 
} 
+0

你收到任何錯誤訊息? – Rizier123

+0

注意SQL注入並使用MySQLi。 –

+2

請[不要使用'mysql_ *'函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。他們不再被維護,並[正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。學習[準備的語句](http://en.wikipedia.org/wiki/Prepared_statement),並使用[PDO](http://us1.php.net/pdo)或[MySQLi](http:// us1.php.net/mysqli)。 –

回答

0

讓我說,我不會編寫這樣的說法,但這裏是我會做什麼來糾正你的代碼,同時保持你的結構:

include($_SERVER['DOCUMENT_ROOT']."/database.php"); // your database connection values that are into a $database variable that we will use now. For example, mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD); 

public function register ($username, $password, $activationcode){ 
    $username = $this->parse($username); 
    $password = $this->parse($password); 

    mysqli_select_db(DB_NAME); // the name of the database you will use. 

    $sql = mysqli_query($database, "SELECT * from tbl_user WHERE username = '$username'") or die(mysqli_error()); 

    if(mysqli_num_rows($sql) == 0){ 
     $newUser = "INSERT INTO tbl_user (username, password, activationcode) VALUES ('$username', '$password', '$activationcode')"; 
     if(mysqli_query($database, $newUser)){ 
      return 1; 
     } else { 
      return -1; // you might get a problem in here too. 
     } 
    } else { 
     return -1; 
    } 
}