2015-09-26 62 views
-1

我想要做的是在提交此表單時。它檢查數據庫中匹配用戶名的firstname字段是否爲空。如果爲空,那麼用戶應該被重定向到某個地方,如果它不是空的,用戶將被重定向到其他地方。以下是我的代碼,在其中不幸的是不工作。檢查數據庫中的某個字段是否爲空然後重定向

<?php 
include_once 'db_connect.php'; 
include_once 'functions.php'; 

$user = $_SESSION['username']; 

sec_session_start(); // Our custom secure way of starting a PHP session. 

if (isset($_POST['email'], $_POST['p'])) { 
    $email = $_POST['email']; 
    $password = $_POST['p']; // The hashed password. 

    if (login($email, $password, $mysqli) == true) { 
     $server = "localhost"; 
     $user = ""; 
     $pass = ""; 
     $db = ""; 
     $mysqli = new Mysqli($server, $user, $pass, $db) or mysqli_error($mysqli); 
     $firstname = $mysqli->query("SELECT firstname FROM members WHERE username = '$user'")->fetch_object()->firstname; 
     if(empty($firstname)) { 
      // Login success 
      header('Location: ../updateinfo.php'); 
     } else { 
      header('Location: ../services.php'); 
     } 
    } else { 
     // Login failed 
     header('Location: ../index.php?error=1'); 
    } 
} else { 
    // The correct POST variables were not sent to this page. 
    echo 'Invalid Request'; 
} 

任何想法我錯了?您執行的查詢權之前

$user = ""; 

:因爲你設置

+2

是什麼問題?它是否將一個非空值視爲空,反之亦然? – Barmar

+0

沒有它根本不工作。它在任何情況下都會保持重定向到updateinfo.php。 –

+0

@Barmar當我試圖做!空($ firstname)它重定向到services.php –

回答

1

您的查詢將不會找到任何東西。

"SELECT firstname FROM members WHERE username = '$user'" 

如前所述Barman,這是最有可能使用的$_SESSION['username']相同$user變量和數據庫用戶名一,你的結果。

將其中一個改爲別的。

在開始會話之前,您還試圖獲取會話變量。您必須先開始會話。

// Switch the order of these two. 
$user = $_SESSION['username']; 

sec_session_start(); // Our custom secure way of starting a PHP session. 
+0

問題是他爲$ _SESSION ['username']'和數據庫訪問用戶名使用相同的$ user變量。 – Barmar

+0

改變了它,固定但仍然不起作用。 –

0

從我可以看到,在這個例子中,是$ firstname是查詢的結果(查詢的快照結果)。如果查詢返回零行,則isEmpty($ firstname)將爲空,表示未找到該用戶。

您將需要檢查返回的行的結果,該結果只有一列(或字段)。如果該字段爲空,則可以重定向到updateinfo.php。

例子:

if(empty($firstname)) { 
    // user not found/no records returned 
} else { 
    //fetch first row of returned data set 
    //check if first name is empty 
    // if empty: 
    header('Location: ../updateinfo.php'); 
    //else 
    header('Location: ../services.php'); 
} 

你必須原諒非特定的代碼。我習慣於使用mysql,而不是mysqli。 :)

+0

滾動到右側。他用' - > fetch_object()'獲取第一行。 – Barmar

+0

哎呀,謝謝! – 2015-09-26 00:36:01