检查数据库中的某个字段是否为空,然后重定向

时间:2015-09-26 00:03:59

标签: php mysqli

我尝试做的是提交此表单时。它检查匹配用户名的数据库中的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';
}

知道我哪里出错了吗?

2 个答案:

答案 0 :(得分:1)

您的查询永远找不到任何内容,因为您设置了:

$user = "";

在您执行查询之前。

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

提到Barman时,这很可能是因为$user使用相同的$_SESSION['username']变量和数据库用户名。

将其中一个更改为其他内容。

您还尝试在启动会话之前获取会话变量。你必须先开始会议。

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

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

答案 1 :(得分: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。 :)

相关问题