2011-08-06 90 views
0

有人能夠給我一個MySQL關係查詢來查找基於另一個同一個表的值的表的列值嗎?查詢基於用戶電子郵件的ID查找

例如,我有一個4列(id,名稱,電子郵件,密碼)表。我如何根據他們的電子郵件在「email」列中查找某個用戶的「id」列的值,並將結果(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(...);如果(mysql_num_rows(...)== 1){ $ r = mysql_fetch ...; $ author = $ r ['id']; }' –

+0

同意。通常我會,我只是想我會在這裏嘗試新的東西。 –