2015-12-31 75 views
0

我有一個客戶表。每個客戶都有一個特定的ID。 在我的項目(ecommerce website)中,我想在成功登錄時將用戶的ID存儲在$ _SESSION ['user_id']中。 我該怎麼做?我需要添加什麼? 這裏是我的代碼:使用php獲取標識

<?php 
// establishing the MySQLi connection 
$con = mysqli_connect("localhost","root","","ecommerce"); 
// checking the user 
if(isset($_POST['login'])){ 
    $email = mysqli_real_escape_string($con,$_POST['c_email']); 
    $pass = mysqli_real_escape_string($con,$_POST['pass']); 
    $sel_user = "select * from customer where customer_email ='$email' AND customer_pass='$pass'"; 
    $run_user = mysqli_query($con, $sel_user); 
    $check_user = mysqli_num_rows($run_user); 
    if($check_user>0){ 
     $_SESSION['customer_email']=$email; 
     echo "<script>window.open('index.php','_self')</script>"; 
    } else { 
     echo "<script>alert('Email or password is not correct, try again!')</script>"; 
    } 
} 
?> 
+0

開始會話。 http://php.net/manual/en/function.session-start.php你也可以使用'header'而不是'echo「」'。 – chris85

+0

呵呵,然後讓userid對查詢結果運行一個提取並將用戶標識存儲在會話變量中。 – chris85

+1

你應該[hash](http://php.net/manual/en/faq.passwords.php )你的密碼,並利用MySQLi的[準備語句](http://php.net/manual/en/mysqli.prepare.php)。 – Script47

回答

1

首先,@ chris85提到的,叫session_start()在你的腳本的頂部。

然後,你快到了。首先,您需要從結果中獲取結果對象。

$rows = array(); 

while ($row = mysql_fetch_assoc($run_user)) { 
    $rows[] = $row; // Same as array_push($rows, $row) but has better performance when pushing a single item. 
} 

然後,假設我們知道,只有一個返回行:

$customerData = $rows[0]; 

酷。現在,設定任何你想要的Session變量:

$_SESSION["user_id"] = $customerData["user_id"]; 
... 

此外,由於已經注意到在評論,請請請永遠不存儲用戶的密碼爲純文本。你應該散列和鹽。這裏是一個很好的入門文章,通讀:Best way to store password in database

+0

謝謝!節日快樂! – Jerlon

+0

跟進問題,這是可能的聲明? '\t $ user_login =「select * from customer where customer_email ='$ _SESSION ['email']'」;' – Jerlon

+0

我的意思是,我允許在查詢中使用$ _SESSION ['email']變量嗎? Sublime似乎突出了$ _SESSION ['']'索引內的「email」字樣的背景。 – Jerlon