2015-12-31 71 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