I've been trying to get logged persons user_id
which is in user_login
table in my database and insert it to the another table.
What I know is, get the user_id
from the user_login
using query and assign that query to the SESSION variable and put that variable in another query where I want to insert it in the table but I'm unable to write a perfect code for it.The only thing I'm achieving is it taking the user_id
as 1 in the new table.It would be a great help if you can review my code correct it.
<?php
ob_start();
include ('header.php');
require('includes/connect.php');
require('includes/product.php');
$product = new Product;
if(isset ($_GET['id'])) {
$id = $_GET['id'];
$data = $product -> fetch_data($id);
if(isset($_POST['add'])){
if (isset($_SESSION['logged_in'])) {
$query = $pdo->prepare("SELECT user_id FROM user_login ");
$user_id=$query->execute();
$_SESSION['user_id']['id']=$user_id;
$query = $pdo -> prepare("INSERT INTO cart_items(product_id , user_id, Price) VALUES (?,?,?)");
$query -> bindValue(1, $id);
$query -> bindValue(2, $_SESSION['user_id']['id']);
$query -> bindValue(3, $data['new_price']);
$query ->execute();
header('location:cart.php');
}
else{
header('location:Login Page.php');
}
}
?>
This is where I have done the user validation while logging in (connect.php)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "ecom";
try{
$pdo = new PDO('mysql:host=localhost;dbname=ecom','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
exit('Database error.');
}
function login(){
global $pdo;
$username = $_POST['email'];
$password = md5($_POST['password']);
if(empty($username) or empty($password))
{
$error = "Please fill all the fields";
}
else
{
$query = $pdo->prepare("SELECT * FROM user_login WHERE name = ? AND password = ? ");
$query->bindValue ( 1, $username);
$query->bindValue ( 2, $password);
$query->execute();
$num=$query->rowCount();
if($num==1) {
$_SESSION['logged_in']= true;
//header('location :' .$_SESSION['redirectURL']);
header('location: index.php');
exit();
}
else{
$error = "Please enter correct Username and Password";
}
}
}
?>
Thank you in advance.