Reputation: 269
I have a customer table. Each customer has a specific ID.
In my project(ecommerce website
) I want to store the ID of the user in a $_SESSION['user_id'] when he/she successfully login.
How do I do that? What do I need to add?
Here's my code:
<?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>";
}
}
?>
Upvotes: 0
Views: 65
Reputation: 31963
First, as @chris85 mentioned, call session_start()
at the top of your script.
Then, you're almost there. First, you need to get the result object from the results.
$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.
}
Then, assuming we know there is only one row returned:
$customerData = $rows[0];
Cool. Now, set whatever SESSION variables you want:
$_SESSION["user_id"] = $customerData["user_id"];
...
Also, as has been noted in the comments, please please please do not ever store a user's password as plain text. You should hash and salt it. Here is a good starter post to read through: Best way to store password in database
Upvotes: 1