我有一张客户表。每个客户都有一个特定的ID。
在我的项目(ecommerce website
)中,我想在用户成功登录时将其存储在$ _SESSION ['user_id']中。
我怎么做?我需要添加什么?
这是我的代码:
<?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 :(得分: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