用户登录php时需要帮助显示用户名

时间:2014-06-20 20:16:19

标签: php html sql html5

所以下面我有我的PHP代码,除了当用户登录并被重定向到受限页面时,一切正常和花花公子。当一个人注册时,他们会填写他们的名字,电子邮件和密码。在登录页面中,它只需要电子邮件和密码。当他们被重定向时,我想只显示他们的名字。我试过使session = $ result应该返回sql查询的结果,但如果我这样做,它甚至不会重定向到受限制的页面。我做错了什么?

<?php

// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";

// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);

// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;

// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {

    // STORES INPUTS AS VARIABLES
    $email = $_POST['email'];
    $password = $_POST['password'];

    // REMOVES HARMFUL CODE
    $email = htmlspecialchars($email);
    $password = htmlspecialchars($password);

    if ($db_found) {

        $SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
        $result = mysql_query($SQL);
        $num_rows = mysql_num_rows($result);

        if ($num_rows > 0) {

            session_start();
            $_SESSION['login'] = ?;
            header ("Location: loggedin/account.php");

        }
        else {

            session_start();
            $_SESSION['login'] = '';

        }

    }
    else {

    }

}
?>

2 个答案:

答案 0 :(得分:1)

这就是我要做的......

// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";

// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);

// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;

// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {

// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];

// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);

if ($db_found) {

    $SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
    $result = mysql_query($SQL);
    $num_rows = mysql_num_rows($result);

//从db

中获取用户名
    $row = mysql_fetch_row($result);
    if ($num_rows > 0) {

//添加到会话变量

        session_start();
        $_SESSION['login'] = $row['username'];
        header ("Location: loggedin/account.php");

    }
    else {

//退出或重定向到登录失败页面。

    }

}
else {

虽然我目前无法测试,但这对我来说似乎没问题。

修改 您可能希望阅读使用Mysqli和PDO连接,它稍微快一点,绝对更安全,只是一个建议,如果你有时间。准备好的陈述肯定会更多安全。

答案 1 :(得分:0)

这就是我登录的方式......你必须拥有mysql中每个用户的ID并定义

$_SESSION['user_id'] = $fetched_id;

在loggedin / account.php页面中,你可以简单地做到这一点:

$user_id = $_SESSION['user_id'];
$query = mysql_query("SELECT `first_name` FROM `users` WHERE `id` = '{$user_id}'");