2011-08-06 3 views
0

누군가가 같은 테이블의 다른 값을 기반으로 테이블의 열 값을 조회하기 위해 MySQL 릴레이션 쿼리를 제공 할 수 있습니까?사용자 이메일 기반 ID 조회 쿼리

예를 들어 4 개의 열 (ID, 이름, 전자 메일, 암호)이있는 테이블이 있습니다. 특정 사용자의 "id"열의 값을 "email"열의 전자 메일을 기반으로 조회하고 결과 (id)를 변수에 저장할 수 있습니까?

다음은 세션() 컨트롤러 기능

function userIsLoggedIn() 
{ 
    if (isset($_POST['action']) and $_POST['action'] == 'login') 
    { 
     if (!isset($_POST['email']) or $_POST['email'] == '' or 
      !isset($_POST['password']) or $_POST['password'] == '') 
     { 
      $GLOBALS['loginError'] = 'Please fill in both fields'; 
      return FALSE; 
     } 

     $password = md5($_POST['password'] . 'chainfire db'); 

     if (databaseContainsAuthor($_POST['email'], $password)) 
     { 
      session_start(); 
      $_SESSION['loggedIn'] = TRUE; 
      $_SESSION['email'] = $_POST['email']; 
      $_SESSION['password'] = $password; 
      $_SESSION['authorid'] = $author; 
      return TRUE; 
     } 
     else 
     { 
      session_start(); 
      unset($_SESSION['loggedIn']); 
      unset($_SESSION['email']); 
      unset($_SESSION['password']); 
      unset($_SESSION['authorid']); 
      $GLOBALS['loginError'] = 
        'The specified email address or password was incorrect.'; 
      return FALSE; 
     } 
    } 

내가

SELECT id FROM article WHERE email='$email' 

그것을 할 수있는 더 효율적인 방법이 있나요

을 시도했습니다입니까? 나는 또한 쿼리 결과를 $author 세션 변수에 저장하는 방법을 완전히 알지 못합니다.

미리 감사드립니다.

답변

1

검색어가 완벽합니다 ($email 변수를 살균하는 경우 - 이야기는 Little Bobby Tables 참조).

SELECT id FROM article WHERE email='$email' 

그리고 쿼리를 수행하고 반환 된 값으로 변수 $author을 설정은 간단하다 : 위에서 따라 너무 복잡 경우

$author = 0; 
if(($idFromEmail = @mysql_query("SELECT id FROM article WHERE email='".mysql_real_escape_string($email)."'")) 
    && mysql_num_rows($idFromEmail)==1 
    && ($r = mysql_fetch_assoc($idFromEmail))){ 
    $author = $r['id']; 
} 

가 긴 형태로 재 작성 :

$author = 0; 
if(!($idFromEmail = @mysql_query("SELECT id FROM article WHERE email='".mysql_real_escape_string($email)."'")){ 
    // SQL Query Failed 
}elseif(mysql_num_rows($idFromEmail)!=1){ 
    // More than, or less than, one row returned 
}else{ 
    $r = mysql_fetch_assoc($idFromEmail); 
    $author = $r['id']; 
} 
+0

모든 코드를 별도의 줄에 써서 코드를 좀 더 읽기 쉽게 만들 것을 제안합니다. 즉,'$ idFromMail = mysql_query (...); if (mysql_num_rows (...) == 1) { $ r = mysql_fetch ...; $ author = $ r [ 'id']; }' –

+0

동의합니다. 평소에 나는 뭔가 새로운 것을 시도 할 것이라고 생각했습니다. –