我是 PHP 新手。 我制作了一个登录页面和一个注册页面,我想在成功登录或注册后将客户 ID 存储在我的 session 变量中,以便稍后在我的购物车文件中使用 session 变量来检索该客户的购物车详细信息。客户 ID 在表中自动递增,因此我不会从客户那里获取客户 ID 的输入。 这是代码
登录.php:
<?php
session_start();
$db=mysqli_connect("localhost","root","Naruto97","musicgallery");
if (isset($_POST['login_btn'])){
$email = mysqli_real_escape_string($db,$_POST['email']);
$password = mysqli_real_escape_string($db,$_POST['password']);
$password=md5($password);
$sql="SELECT * FROM LoginCredentials WHERE email='$email' AND password='$password'";
$result = mysqli_query($db,$sql);
if(mysqli_num_rows($result)==1){
$_SESSION['message']="You are now logged in";
$_SESSION['email']=$email;
//Want to store the customer in session variable here after successful login
header("location:home.php");
}
else{
$_SESSION['message']= "Email/Password combination Incorrect";
}
}
?>
注册.php:
<?php
session_start();
$db=mysqli_connect("localhost","root","Naruto97","musicgallery");
if (isset($_POST['register_btn'])){
$username = mysqli_real_escape_string($db,$_POST['username']);
$email = mysqli_real_escape_string($db,$_POST['email']);
$password = mysqli_real_escape_string($db,$_POST['password']);
$password2 = mysqli_real_escape_string($db,$_POST['password2']);
if($password==$password2){
$password=md5($password);
$sql = "INSERT INTO LoginCredentials(Username,email,password) VALUES('$username','$email','$password')";
mysqli_query($db, $sql);
$_SESSION['message']="You are now logged in";
$_SESSION['email']=$email;
//Want to store the customer_id here in the session variable after successful registration
header("location:home.php");
}else{
$_SESSION['message']="The passwords do not match";
}
}
?>
购物车.php:
<?php
session_start();
$db=mysqli_connect("localhost","root","Naruto97","musicgallery");
if(isset($_POST["add_to_cart"])){
if(isset($_SESSION['email'])){
$album_name = mysqli_real_escape_string($db,$_POST['hidden_name']);
$price = mysqli_real_escape_string($db,$_POST['hidden_price']);
$quantity = mysqli_real_escape_string($db,$_POST['quantity']);
//$customer_id= $_SESSION['customer_id'];
$sql = "INSERT INTO cart(album_name,price,quantity,customer_id) VALUES('$album_name','$price','$quantity','$customer_id')";
mysqli_query($db, $sql);
echo "<script>alert('Added to cart')</script>";
echo "<script>window.location('kpop.php')</script>";
}
else
{
echo "<script>alert('Please Login')</script>";
echo "<script>window.location('kpop.php')</script>";
}
}
?>
最佳答案
要获取 mysqli 中的最后一个 insertid,请使用:-
$sql = "INSERT INTO cart(album_name,price,quantity,customer_id) VALUES('$album_name','$price','$quantity','$customer_id')";
mysqli_query($db, $sql);
$_SESSION['customerId']=mysqli_insert_id($db);//gets the last inserted customerid from db
如需进一步引用,您可以查看此 link .
关于php - 如何从 mysql 获取客户 ID,然后将其存储在 session 变量中以使用另一个文件中的 session 变量来检索信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47405020/