2016-09-06 3 views
-3

사용자 가입 페이지의 데이터베이스 내에 사용자 이름이 이미 존재하는지 확인하고 싶습니다. 입력 한 사용자 이름으로 선택 쿼리를 수행하고 얼마나 많은 결과가 나오는지 알 수 있습니다. 돌아와. 그러나 num_rows는 항상 = -1입니다. 사용하고있는 테스트 사용자 이름은 데이터베이스에 두 번 있기 때문에 입력 할 때 다른 사용자에게 가서 "이 사용자는 이미 있습니다"라고 인쇄해야합니다. 나는 mysqli에 대해서 조금 새로운 것이기 때문에 만약 여러분이 그 에러를 보았다면, 여러분의 의견은 크게 감사 할 것입니다.OO MYSQLI num_rows always = -1

내 PHP는 여기에 있습니다 :

  <?php 
      if(isset($_POST['submit'])){ 
        $connection = new mysqli("localhost","username","password","DB"); 
        if($connection->connect_errno){ 
          echo "Failed to connecto MYSQL: (" . $connection->connect_errno . ") " . $connection-> connect_error; 
        } 
        else{ 
          $username = $_POST['username']; 
          $password = $_POST['password']; 
          $password = password_hash($password, PASSWORD_DEFAULT); 
          $check_exist = $connection->prepare("SELECT username FROM users WHERE username = ?"); 
          $check_exist->bind_param('s', $username); 
          $username = $connection->real_escape_string($username); 
          $check_exist->execute(); 
          $check_exist->store_result(); 
          $numRows = $check_exist->num_rows(); 
          if($numRows = -1){ 
            echo "$numRows"; 
            $enter_user = $connection->prepare("INSERT INTO users (username, password) VALUES (?,?)"); 
            $enter_user->bind_param('ss', $username, $password); 
            $enter_user->execute(); 
            $enter_user->store_result(); 
            $check_exist->close(); 
            $enter_user->close(); 
            $connection->close(); 
          } 
          else{ 
            echo "This user already exists."; 
            $check_exist->close(); 
            $connection->close(); 
          } 
        } 
      } 
      ?> 

죄송 서식, 내가 여기에 새로운 조금 ...

+3

'$ numRows = -1' <- 항상 $ numRows에 -1의 값을 할당합니다. –

+1

'users' 테이블의'username' 열에'UNIQUE' 제약 조건을 추가하면됩니다. 삽입하기 전에'SELECT'에 의존하면 삽입 할 중복 레코드를위한 작은 창이 남습니다. 이로 인해 심각한 보안 문제가 발생할 수 있습니다. – Chris

+0

@JohnConde 그래서 = = ==로 변경했고 이제는 사용자가 존재하지 않더라도 항상 Else ...가 기본값이됩니다. – Doncho

답변

0

라인 "만약 ($ numRows의 = -1)을 {"이야을 의미 "if ($ numRows == -1)"을 코드화하고 $ numRows 값을 -1로 설정합니다.

"if (! $ numRows) {"를 사용할 수 있습니다.

관련 문제