0

我被困在如何为登录的用户创建会话。我得到了检查以确保登录信息与数据库信息一致的部分,但被困在如何获取电子邮件地址并将其存储到会议。下面是我的 php 代码。

<?php include '../View/header.php';
session_start();
require('../model/database.php');
$email = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT emailAddress FROM customers WHERE emailAddress ='$email' AND password = '$password'";
$result = mysql_query($sql, $db);

if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_assoc($result)) {
    echo $row['emailAddress'];
}

mysql_free_result($result);

?>
4

4 回答 4

1

试试下面的。

请注意这个mysql连接类型已经被贬值了,查一下PDO。您还需要阅读 sql injection,因为这不安全。

<?php 
    //always put session_start() at the top of the file
    session_start();

    include('../View/header.php');
    require ('../model/database.php');

    $email = $_POST['username'];
    $password = $_POST['password'];  

    $sql = "SELECT emailAddress FROM customers WHERE emailAddress = '$email' AND password = '$password'";
    $result = mysql_query($sql, $db);

    if(!$result){
        echo "DB Error, could not query the database\n";
        echo 'MySQL Error: ' . mysql_error();
        exit;
    }

    while($row = mysql_fetch_assoc($result)) {
        echo $row['emailAddress'];
        $_SESSION['email'] = $row['emailAddress'];
        $_SESSION['batmansName'] = "Bruce Wayne";
    }

    mysql_free_result($result);

?>`
<a href="anotherFile.php">Click to output the contents of our session :)</a>

另一个文件.php

<?php

    //always put session_start() at the top of the file
    session_start();

    //print out everything that we have stored in the session
    print_r($_SESSION);

    echo "<br /><br />";

    echo "Session email: ".$_SESSION['email']."<br />";
    echo "Batman's real name: ".$_SESSION['batmansName']."<br />";


?>
于 2013-11-03T21:58:21.430 回答
0

你的头文件有任何输出吗?如果是这样,您将需要放在session_start它前面,以便它可以设置标题。如果不这样做,您的会话数据将不会被保留。

接下来,为了在会话中存储数据,我们使用$_SESSION超全局

$_SESSION['email'] = $row['emailAddress'];
于 2013-11-03T21:49:35.073 回答
0
  1. 在打印任何内容之前开始会话
  2. 使用 $_SESSION 存储用户数据

例子:

session_start();
include '../View/header.php';
require ('../model/database.php');
$email= $_POST['username'];
$password= $_POST['password'];  
$sql    = "SELECT emailAddress FROM customers WHERE emailAddress ='$email' AND password = '$password'";
$result = mysql_query($sql, $db);

if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

if ($row = mysql_fetch_assoc($result)) {
     $_SESSION['user_address'] = $row['emailAddress'];
}

mysql_free_result($result);
于 2013-11-03T21:51:42.490 回答
0

首先,请阅读 SQL-Injections:http ://de.wikipedia.org/wiki/SQL-Injection ,因为您的代码存在重大安全问题

其次,您必须session_start();在包含标题之前调用,如果在调用之前已将任何内容发送到浏览器,它将不起作用。

于 2013-11-03T21:52:37.177 回答