2013-11-03 197 views
0

我被困在如何爲登錄用戶創建會話。我得到了檢查的一部分,以確保登錄信息與數據庫信息相對應,但被困在如何採取電子郵件地址並存儲到會話中。下面是我的php代碼。創建會話用戶登錄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); 

?> 
+0

你問如何存儲的電子郵件地址,即查詢結果爲會議? (此外,不需要從數據庫中獲取相同的電子郵件地址,這與您在'WHERE'子句中提供的相同)。 – Lion

回答

0

您的頭文件是否執行任何類型的輸出?如果是這樣,你會想把session_start放在它之前,這樣它可以設置標題。如果沒有完成,您的會話數據將不會保留。

接下來,我們使用$_SESSION超全局

$_SESSION['email'] = $row['emailAddress']; 
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); 
0

首先,請閱讀SQL注入:http://de.wikipedia.org/wiki/SQL-Injection,因爲您的代碼有一個主要的安全問題

其次,在添加標題之前,您必須先致電session_start();,如果在調用之前發送了任何內容到瀏覽器,它將不起作用。

1

請嘗試以下操作。

請注意,此mysql連接類型已被折舊,查找PDO。你也需要閱讀SQL注入,因爲這是不安全的。

<?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> 

anotherFile.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 />"; 


?>