3

我昨晚刚开始学习 mysqli,目前我创建的函数有问题。该功能应登录用户。但是,当我使用真实密码或编造密码输入现有用户名时,登录页面会重新加载并显示$user_id. 我对出了什么问题感到迷茫。我有mysql的时候没有这个问题。

/** 
 * Returns FALSE, if no valid user found
 * Returns user_id of matching user with $username and $password
 */
function login ($mysqli, $username, $password) {

    // not required at all
    // $user_id = user_id_from_username($mysqli, $username);

    // initialize, in case we do not get a mysqli-statement
    $userID = FALSE;
    $password = md5($password);
    $stmt = $mysqli->prepare(
                     "SELECT `user_id`          "
                   . "  FROM `users`            "
                   . " WHERE ( `username` = ? ) "
                   . "   AND ( `password` = ? ) "
            );

    if ( $stmt ) {
        $stmt->bind_param('ss', $username, $password);  
        $stmt->execute();
        $stmt->bind_result($userID);
        if ( TRUE !== $stmt->fetch()) {
            $userID = FALSE;
        }
    }
    $stmt->close();
    return $userID; 
}

这是我在登录页面中调用函数登录的时候。$mysqli是包含与数据库的连接的变量。

// Now, needs to check against FALSE to work [changed by @SteAp]

//   var_dump( $login ); returns with int(1) 
//   and this is what I want, the integer 1

//Sends me to start.php but start.php does not recognize 
//the variable $_SESSION['user_id']
if ( FALSE === ($login = login($mysqli, $username, $password)) ) {  
  $errors[] = 'That username/password combination is incorrect';
} else {
  $_SESSION['user_id'] = $login;
  header('Location: start.php');
  exit();
}

if (empty($errors) === false) {
  echo '<div>'. output_errors($errors) . '</div>';
}
4

2 回答 2

1

替换以下行:

if ($return == 1) {echo $user_id;} else {return false;}

if ($return == 1) {return $user_id;} else {return false;}

在您的示例中,您正在$user_id浏览器中编写变量,而不是将其返回给调用它的函数。

于 2012-09-01T22:40:26.017 回答
0

返回 user_id,而不是计数:

if ($stmt = $mysqli->prepare("SELECT `user_id` FROM `users` WHERE `username` = ? 

然后像这样使用它:

$stmt->bind_result($return);

if ( TRUE !== $stmt->fetch() ) {
  $return = FALSE
}

$stmt->close();

return $return;

现在,$return如果找到记录中的一个FALSE或一个。user_id

而且,当然,您需要在对 $_SESSION 的任何分配传递之前启动一个会话PHP手册中的示例:

page1.php

session_start();

echo 'Welcome to page #1';

$_SESSION['favcolor'] = 'green';
$_SESSION['animal']   = 'cat';
$_SESSION['time']     = time();

// Works if session cookie was accepted
echo '<br /><a href="page2.php">page 2</a>';

page2.php

session_start();

echo 'Welcome to page #2<br />';

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal'];   // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// You may want to use SID here, like we did in page1.php
echo '<br /><a href="page1.php">page 1</a>';
于 2012-09-01T22:42:23.800 回答