2015-01-05 34 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; 
    } 
}