Why my $_SESSION["products"] has been destroy after logged in, How do I keep my $_SESSION["products"] after I logged in?
Add product to cart before logged in.
After logged in my cart is empty.
CODE
login.php
<?php
ob_start();
session_start();
include 'init.php';
require_once 'config.php';
//initalize user class
$user_obj = new Cl_User();
if(!empty( $_POST )){
try {
$user_obj = new Cl_User();
$data = $user_obj->login( $_POST );
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
header('Location: home.php');
}
} catch (Exception $e) {
$error = $e->getMessage();
}
}
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
header('Location: home.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Smart Login Page</title>
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<?php require_once 'templates/ads.php';?>
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">Login</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form id="login-form" method="post" class="form-signin" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="email" id="email" type="email" class="form-control" placeholder="Email" autofocus>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<button class="btn btn-block bt-login" type="submit" id="submit_btn" data-loading-text="loging in....">Login</button>
<br>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot Password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign up
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/login.js"></script>
</body>
</html>
<?php ob_end_flush(); ?>
login function in User.php
public function login( array $data )
{
$_SESSION['logged_in'] = false;
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$email = mysqli_real_escape_string( $this->_con, $trimmed_data['email'] );
$password = mysqli_real_escape_string( $this->_con, $trimmed_data['password'] );
if((!$email) || (!$password) ) {
throw new Exception( LOGIN_FIELDS_MISSING );
}
$password = md5( $password );
$query = "SELECT member_id, member_display_name, member_email, member_status, roles_id FROM fm_member where member_email = '$email' and member_pwd = '$password' ";
//$query = "SELECT user_id, name, email, created, roles_id, id FROM users where email = '$email' and password = '$password'"
$result = mysqli_query($this->_con, $query);
$data = mysqli_fetch_assoc($result);
$count = mysqli_num_rows($result);
mysqli_close($this->_con);
if( $count == 1){
$_SESSION = $data;
if($_SESSION['member_status'] == 'Activated') {
$_SESSION['logged_in'] = true;
return true;
} else {
throw new Exception( 'Your account is Deactiavted! <br> Please contact to Adminnistrator for more information.' );
$_SESSION['logged_in'] = false;
}
}else{
throw new Exception( LOGIN_FAIL );
}
} else{
throw new Exception( LOGIN_FIELDS_MISSING );
}
}
cart_process.php
session_start(); //start session
include_once("config.inc.php"); //include config file
setlocale(LC_MONETARY,"en_US"); // US national format (see : http://php.net/money_format)
############# add products to session #########################
if(isset($_POST["product_code"]))
{
foreach($_POST as $key => $value){
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); //create a new product array
}
//we need to get product name and price from database.
$statement = $mysqli_conn->prepare("SELECT fm_product.p_name, fm_product.p_price, fm_product.p_member_id, fm_product.p_discount, fm_member.member_display_name, fm_member.member_payment, fm_product_image.img_1, shipping_cost.shipping_register,
shipping_cost.shipping_normal, shipping_cost.shipping_ems FROM fm_product LEFT JOIN fm_member ON fm_member.member_id = fm_product.p_member_id LEFT JOIN fm_product_image ON fm_product_image.p_id_img = fm_product.p_id LEFT JOIN shipping_cost ON shipping_cost.shipping_vendor = fm_member.member_id WHERE p_id=?");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $product_price, $p_member_id, $p_discount, $member_display_name, $member_payment, $img_1, $shipping_register, $shipping_normal,$shipping_ems);
while($statement->fetch()){
$new_product["p_name"] = $product_name; //fetch product name from database
$new_product["p_price"] = $product_price;
$new_product["p_member_id"] = $p_member_id;
$new_product["p_discount"] = $p_discount;
$new_product["member_display_name"] = $member_display_name;
$new_product["member_payment"] = $member_payment;
$new_product["img_1"] = $img_1;
$new_product["shipping_register"] = $shipping_register;
$new_product["shipping_normal"] = $shipping_normal;
$new_product["shipping_ems"] = $shipping_ems;
//fetch product price from database
if(isset($_SESSION["products"])){ //if session var already exist
if(isset($_SESSION["products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["products"][$new_product['product_code']]); //unset old item
}
}
$_SESSION["products"][$new_product['product_code']] = $new_product; //update products with new item array
}
$total_items = count($_SESSION["products"]); //count total items
die(json_encode(array('items'=>$total_items))); //output json
}
################## list products in cart ###################
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){ //if we have session variable
$cart_box = '<ul class="cart-products-loaded">';
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
//set variables to use them in HTML content below
$product_name = $product["p_name"];
if(!empty($product["p_discount"]))
{
$product_price = $product["p_discount"];
} else if(empty($product["p_discount"])) {
$product_price = $product["p_price"];
}
$product_code = $product["product_code"];
$p_member_id = $product["p_member_id"];
$member_display_name = $product["member_display_name"];
$member_payment = $product["member_payment"];
$product["product_qty"] = 1;
$product_qty = $product["product_qty"];
$cart_box .= "<li>$product_name — Price ".$product_price." x ".$product_qty." = ".sprintf($product_qty * $product_price)."×</li>";
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
$cart_box .= "</ul>";
$cart_box .= '<div class="cart-products-total" style="border-top: 1px solid #C0C0C0;">'.$quantity.'Total : '.sprintf($total).'<u>Check Out</u></div>';
die($cart_box); //exit and output content
}else{
die("Empty Cart!"); //we have empty cart
}
}
EDIT
home.php added
<?php
session_start();
include('connect.php');
$ID = $_SESSION['member_id'];
if(!isset($_SESSION['logged_in'])){
header('Location: index.php');
}
?>
<?php require_once 'templates/header.php';?>
<?php if($_SESSION['roles_id']=='1') { ?>
<div class="content">
<div class="container">
<div class="col-md-8 col-sm-8 col-xs-12">
<br>
<h1 class="text-center"> Admin Page </h1>
<br>
</div>
<?php require_once 'templates/sidebar.php';?>
</div>
</div> <!-- /container -->
<?php } else if($_SESSION['roles_id']=='2') { ?>
<div class="content">
<div class="container">
<div class="col-md-8 col-sm-8 col-xs-12">
<br>
<h1 class="text-center"> User Page </h1>
<br>
</div>
<?php require_once 'templates/sidebar.php';?>
</div>
</div> <!-- /container -->
<?php } ?>
looks like $_SESSION = $data; may be your culprit, you're resetting the entire session variable with data.
EDIT
Where $_SESSION = $data is change it to this;
$data["products"] = $_SESSION["products"];
$_SESSION = $data;
Related
The problem is that i want to change the quantity of the ticket remaining but when i try to submit my input value the code doesn't change the value of mySQL, But at first when the buy button did change the remaining tickets it removed all of them instead of the input value of 1 to 8.
my PHP:
<?php
session_start();
?>
<!DOCTYPE html>
WinterValley | Tickets
<style>
<?php include '../style.css'; ?>
</style>
<?php
try {
// PDO Connection
$serverName = "localhost";
$dbname = "wintervalley";
$dBUsername = "root";
$dBPassword = "";
$charset = 'utf8mb4';
$dsn = "mysql:host=$serverName;dbname=$dbname;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $dBUsername, $dBPassword, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
// Table connection
$stmt = $pdo->prepare("SELECT * FROM `tickets_finland`");
$stmt->execute();
$tickets_finland_data = $stmt->fetchAll();
$total_tickets_finland = $stmt->fetchColumn();
// Database ticket_pop-up content
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['ticketQuantity_finland'])) {
$ticketQuantity_finland = $_POST['ticketQuantity_finland'];
if (is_numeric($ticketQuantity_finland) && $ticketQuantity_finland >= 1 && $ticketQuantity_finland <= 8) {
// Retrieve current quantity
$stmt = $pdo->prepare("SELECT quantity FROM `tickets_finland` WHERE id = :id");
$stmt->bindParam(':id', $tickets_finland_data[0]['id']);
$stmt->execute();
$total_tickets_finland = $stmt->fetchColumn();
// Update the quantity
$new_total_tickets = $total_tickets_finland - $ticketQuantity_finland;
if ($new_total_tickets >= 0) {
$stmt = $pdo->prepare("UPDATE tickets_finland SET quantity = :new_total_tickets WHERE id = :id");
$stmt->bindParam(':new_total_tickets', $new_total_tickets);
$stmt->bindParam(':id', $tickets_finland_data[0]['id']);
$stmt->execute();
} else {
echo "Invalid input: Not enough tickets available";
}
} else {
echo "Invalid input: Enter a number between 1 and 8";
}
}
}
?>
<!-- logo -->
<img src="../img/logo.png" alt="logo" />
<h1>WinterValley</h1>
<!--login/register -->
<?php
if (isset($_SESSION["useruid"])) {
echo '<a class="log-out-button" href="../include/logout.inc.php">Log out</a>';
} else {
include "../include/login.php";
?> <div class="empty2"></div> <?php
include "../include/register.php";
}
?>
<div class="empty3"></div>
</div>
<!-- navbar -->
<?php include "../include/navbar.php" ?>
<!-- Ticket pop-ups -->
<!-- Ticket pop-up (Finland) -->
<div class="ticketPopupBox">
<div class="ticketPopup" id="ticket_pop-up_finland">
<form class="ticketContainer">
<label for="ticketCheckbox">
<h2 class="popup_ticket_title">
<?php
foreach ($tickets_finland_data as $ticket_fi) {
echo $ticket_fi['event_id'] . "<br>";
}
?></h2>
</label>
<div class="checkbox_info">
<?php
foreach ($tickets_finland_data as $ticket_fi) {
echo "€" . $ticket_fi['ticket_price'] . "<br>";
}
?>
<form method="post" action="../page/tickets.php">
<label for="ticketQuantity">Number of tickets:</label>
<input type="number" id="ticketQuantity_finland" name="ticketQuantity_finland" min="1" max="8" required>
<input type="submit" value="Buy" class="btnTicket">
</form>
<?php
foreach ($tickets_finland_data as $ticket_fi) {
echo $ticket_fi['quantity'] . " Remaining" . "<br>";
}
?>
<div class="ticket_featuring">
<p>Featuring:</p>
<ol>
<li>Sarah Brightman</li>
<li>Ed Sheeran</li>
<li>Kate Bush</li>
<li>Linkin Park</li>
</ol>
</div>
<button type="button" class="btn_cancelTicket" onclick="ticket_closePopupFinland()">Close</button>
</div>
</form>
</div>
</div>
<!-- Ticket info -->
<div class="ticket_box">
<h1 class="ticket_h1">Tickets for Upcoming Events</h1>
<div class="ticket_afstand">
<div class="finland_bg">
<div class="ticket_content">
<h2 class="ticket_head">WinterValley Finland</h2>
<ul>
<li>16:00-00:00</li>
<li>25th February 2023</li>
<li>Eerikinkatu 3, 00100 Helsinki</li>
<div><button onclick="ticket_openPopupFinland()" class="ticket_button">Buy now</button></div>
</ul>
</div>
</div>
</div>
<?php include "../include/footer.php" ?>
<script>
// functie pop-up Finland
function ticket_openPopupFinland() {
document.getElementById("ticket_pop-up_finland").style.display = "block";
}
function ticket_closePopupFinland() {
document.getElementById("ticket_pop-up_finland").style.display = "none";
}
</script>
mySQL code:
CREATE TABLE `tickets_finland` (
`id` int(11) NOT NULL,
`event_id` varchar(255) NOT NULL,
`quantity` int(11) NOT NULL CHECK (`quantity` \<= 2000),
`ticket_price` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
What i want is that if you input a value between 1 to 8 it removes that value from the database.
I'm trying to set a variable to a function that selects a table from a database. It has worked all the other times I have been using the function, but now I get this error message:
Notice: Undefined variable: post in C:\xampp\htdocs\blog\single.php on line 50
Now when I try to use another function that I have and set the same variable it doesn't work either. For some reason on this single.php page it will not recognize the function that I have in another file. The file where functions are lies included in posts.php, in a file called db.php, like this:
single.php :
<?php include('path.php');?>
<?php include('posts.php');
if (isset($_GET['id']))
{
$post = selectOne('posts', ['id' => $_GET['id']]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<!-- Custom Styles -->
<link rel="stylesheet" href="assets/css/style.css">
<title><?php echo $post['title'];?> </title>
</head>
<body>
<div id="fb-root"></div>
<!-- <script>
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src =
'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.2&appId=285071545181837&autoLogAppEvents=1';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script> -->
<!-- header -->
<?php include(ROOT_PATH . "/app/includes/header.php"); ?>
<!-- // header -->
<!-- Page wrapper -->
<div class="page-wrapper">
<!-- content -->
<div class="content clearfix">
<div class="page-content single">
<h2 style="text-align: center;"><?php echo $post['title']; ?></h2>
<br>
<?php echo html_entity_decode($post['body']); ?>
</div>
<div class="sidebar single">
<!-- fb page -->
<!-- // fb page -->
<!-- Popular Posts -->
<div class="section popular">
<h2>Popular</h2>
<div class="post clearfix">
<img src="images/image_1.png">
How to act inspite of your emotions
</div>
<div class="post clearfix">
<img src="images/image_2.png">
How to act inspite of your emotions
</div>
<div class="post clearfix">
<img src="images/image_3.png">
How to act inspite of your emotions
</div>
<div class="post clearfix">
<img src="images/image_4.png">
How to act inspite of your emotions
</div>
<div class="post clearfix">
<img src="images/image_5.png">
How to act inspite of your emotions
</div>
</div>
<!-- // Popular Posts -->
<!-- topics -->
<div class="section topics">
<h2>Topics</h2>
<ul>
<a href="#">
<li>Poems</li>
</a>
<a href="#">
<li>Quotes</li>
</a>
<a href="#">
<li>Fiction</li>
</a>
<a href="#">
<li>Biography</li>
</a>
<a href="#">
<li>Motivation</li>
</a>
<a href="#">
<li>Inspiration</li>
</a>
<a href="#">
<li>Life Lessons</li>
</a>
<a href="#">
<li>Self Development</li>
</a>
</ul>
</div>
<!-- // topics -->
</div>
</div>
<!-- // content -->
</div>
<!-- // page wrapper -->
<!-- FOOTER -->
<?php include(ROOT_PATH . "/app/includes/footer.php"); ?>
<!-- // FOOTER -->
<!-- JQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Slick JS -->
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/slick-carousel#1.8.1/slick/slick.min.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
posts.php:
<?php
include("app/database/db.php");
include("app/helpers/validatePost.php");
$table = 'posts';
$topics = selectAll('topics');
$posts = selectAll($table);
$errors = array();
$title = "";
$id = "";
$body = "";
$topic_id = "";
$published ="";
if (isset($_GET['id'])){
$post = selectOne($table, ['id' => $_GET['id']]);
$id = $post['id'];
$title = $post['title'];
$body = $post['body'];
$topic_id = $post['topic_id'];
$published = $post['published'];
}
if (isset($_GET['delete_id'])){
$count = delete($table, $_GET['delete_id']);
$_SESSION['message'] = "Post deleted succefully";
$_SESSION['type'] = "success";
header("location: " . BASE_URL . "/admin/posts/index.php");
exit();
}
if(isset($_GET['published']) && isset($_GET['p_id'])){
$published = $_GET['published'];
$p_id = $_GET['p_id'];
$count = update($table, $p_id, ['published' => $published]);
$_SESSION['message'] = "Post published state changed";
$_SESSION['type'] = "success";
header("location: " . BASE_URL . "/admin/posts/index.php");
exit();
}
if (isset($_POST['add-post'])){
$errors = validatePost($_POST);
if(!empty($_FILES['image']['name'])){
$image_name = time() . ' _ ' . $_FILES['image']['name'];
$destination = ROOT_PATH . "/assets/images/" . $image_name;
$result = move_uploaded_file($_FILES['image']['tmp_name'], $destination);
if ($result) {
$_POST ['image'] = $image_name;
} else{
array_push($errors, 'failed to upload image');
}
} else{
array_push($errors, "Post image required");
}
if(count($errors) == 0) {
unset($_POST['add-post']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
$_POST['body'] = htmlentities($_POST['body']);
$post_id = create($table, $_POST);
$_SESSION['message'] = "Post created succefully";
$_SESSION['type'] = "success";
header("location: " . BASE_URL . "/admin/posts/index.php");
exit();
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$topic_id = $_POST['topic_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
}
if(isset($_POST['update-post'])){
$errors = validatePost($_POST);
if(!empty($_FILES['image']['name'])){
$image_name = time() . ' _ ' . $_FILES['image']['name'];
$destination = ROOT_PATH . "/assets/images/" . $image_name;
$result = move_uploaded_file($_FILES['image']['tmp_name'], $destination);
if ($result) {
$_POST ['image'] = $image_name;
} else{
array_push($errors, 'failed to upload image');
}
} else{
array_push($errors, "Post image required");
}
if(count($errors) == 0) {
$id = $_POST['id'];
unset($_POST['update-post'], $_POST['id']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
$_POST['body'] = htmlentities($_POST['body']);
$post_id = update($table, $id, $_POST);
$_SESSION['message'] = "Post updated succefully";
$_SESSION['type'] = "success";
header("location: " . BASE_URL . "/admin/posts/index.php");
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$topic_id = $_POST['topic_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
}
db.php: (There are more functions, but i only included the two I tried to use with the variable $post.
function selectOne($table, $conditions)
{
global $conn;
$sql = "SELECT * FROM $table";
//return srecords that match conditions
$i = 0;
foreach($conditions as $key => $value) {
if ($i === 0){
$sql = $sql . " WHERE $key=?";
} else{
$sql = $sql . " AND $key=?";
}
$i++;
}
$sql = $sql . " LIMIT 1";
$stmt = executeQuery($sql, $conditions);
$records = $stmt->get_result()->fetch_assoc();
return $records;
}
function dd($value){
echo "<pre>", print_r($value, true), "</pre>";
die();
}
I am trying to post a $_GET value so it cant insert the variable value into the database using $_SERVER["REQUEST_METHOD"].
<?php require_once("../includes/initialize.php"); ?>
<?php include("../includes/form_validation_card.php"); ?>
<?php $username = $_SESSION['username']; ?>
<?php
if(!isset($_GET['total']) && !isset($_GET['order_id'])){
redirect_to('order_summary.php');
}
$total = $_GET['total'];
$order = $_GET['order_id'];
?>
<?php
$username = $_SESSION['username'];
$sql = "SELECT * FROM customers WHERE username='$username'";
$result_set = $database->query($sql);
$found_user = $database->fetch_array($result_set);
?>
<?php include_layout_template('header2.php'); ?>
<div class="container">
<div class="row">
<br/><br/><?php echo output_message($message); ?>
</div>
<div class="row ">
<div class="jumbo jumbotron-fluid mx-auto d-block" style="height: 500px; width: 440px; background-color:#DCDCDC; border-radius: 5px;" >
<div class="text-center" style="margin: 3px;"><img src="logo/eden_petshop_logo.png" width="32" height="32"/><?php echo $found_user['first_name']; ?> <?php echo $found_user['last_name']; ?></div>
<p class="text-center">order id: #<?php echo $order; ?></p>
<h4 class="display-4 lead text-center">N<?php echo $total; ?></h4>
<div class="col-sm-6 col-sm-offset-3 mx-auto d-block">
<?php echo output_message($message); ?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="post" class="form-horizontal">
<div class="form-group">
<div class="col">
<input type="text" name="card_number" onchange="trim(this)" placeholder="Card Number" class="form-control" id="card_number"/>
<span style="color: #EA4335"><?= $card_number_error; ?></span>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<input type="text" name="mm_yy" class="form-control" onchange="trim(this)" placeholder="MM/YY">
<span style="color: #EA4335"><?= $mm_yy_error; ?></span>
</div>
<div class="col">
<input type="password" name="cvv" class="form-control" onchange="trim(this)" placeholder="CVV">
<span style="color: #EA4335"><?= $cvv_error; ?></span>
</div>
</div>
</div>
<div class="col-sm-12 col-sm-push-3">
<button type="submit" name="submit" value="Pay" class="btn bg-info btn-sm btn-block" onClick="return confirm('Are you sure your details are correct?');">Pay</button>
</div>
</form>
</div>
</div>
</div>
<?php include_layout_template('footer2.php'); ?>
This is the input display page but i am trying to the $total and $order $_GET variables insert into the database... Please note that every other part of the code assignment is working fine.
<?php
//define variables and set them to empty values
$total_error = $order_error = $card_number_error = $mm_yy_error = $cvv_error = "";
$timestamp = strftime("%Y-%m-%d %H:%M:%S", time());
//form is submitted with post method
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["card_number"])){
$card_number_error = "<div class=''>Card number is required</div>";
}else{
$card_number = test_input($_POST["card_number"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^(?=.*?[0-9]).{16,}$/",$card_number)){
$card_number_error = "<div>Only 16 numbers allowed</div>";
}
}
if(empty($_POST["mm_yy"])){
$mm_yy_error = "<div class=''>Card expiry is required</div>";
}else{
$mm_yy = test_input($_POST["mm_yy"]);
//Check if name only contains letters and whitespaces
if(!preg_match("/^(?=.*?[0-9]).{3,}$/",$mm_yy)){
$mm_yy_error = "<div class=''>Only numbers allowed</div>";
}
}
if(empty($_POST["cvv"])){
$cvv_error = "<div class=''>Card verification is required</div>";
}else {
$cvv = test_input($_POST["cvv"]);
//check if username is atleast 7 characters
if(!preg_match("/^(?=.*?[0-9]).{3,}$/",$cvv)){
$cvv_error = "<div class=''>Card verification must not be more than 3 numbers</div>";
}
}
if($card_number_error == "" && $mm_yy_error == "" && $cvv_error == ""){
$token = 'vfjhvbkebecbjDRCWVJEcbkrvlnke24tir7c_zdvbejw968350124';
$token = str_shuffle($token);
$token = substr($token, 0, 15);
$username = $_SESSION['username'];
$sql = "SELECT * FROM customers WHERE username='$username'";
$result_set = $database->query($sql);
$found_user = $database->fetch_array($result_set);
$email = $found_user['email_address'];
$pay = new Payment();
$pay->username = $username;
$pay->order_id = $order;
$pay->total = $total;
$pay->card_number = $card_number;
$pay->expiry = $mm_yy;
$pay->cvv = $cvv;
$pay->transaction_id = $token;
$pay->status = 0;
$pay->created_at = $timestamp;
if($pay->save()){
//$mail = new Mail();
//$mail->email_address = $email_address;
//$mail->send_transaction_confirmation();
unset($_SESSION['shopping_cart']);
$session->message('<div class="btn bg-success">Congratulations!!! Your order has been processed.</div>');
redirect_to('photos.php');
}
}
if(empty($_POST["message"])){
$message = "";
} else{
$message = test_input($_POST["message"]);
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = htmlentities($data);
return $data;
}
?>
Please note that my $order and total are not getting inserted into my database... Any assistance on my preg_match would be appreciated... Thanks in advance.
You need to use $_POST in your broken code instead of $_GET. Notice your working code used $_POST instead, which is why it works.
Below is my Code where user after sucessfully login can enter into website, but then it shows empty with left and right sidebar
I want the dashboard activity to load by default as the user signed in. How can I do that.
Here it is an library managment system whre user can borrow , edit return books and all history is recorded.
<?php
session_start();
error_reporting(0);
include("databaseConnection.php");
$username = $_SESSION['username'];
if($_REQUEST['activity'] == 'logout'){
$username = null;
$username ="";
unset($username);
$_SESSION['username'] = null;
$_SESSION['username'] ="";
unset($_SESSION['username']);
session_destroy();
}
if(empty($username)){
header("location: ../Index.php");
}
?>
<html>
<head>
</head>
<body>
<!--CONTAINER AREA SECTION-->
<div class="containerHome">
<!--HEAD SECTION-->
<div class="headSection">
<?php include("headSection.php"); ?>
</div>
<!--HEAD SECTION-->
<div class="navSection">
<div class="welcomeTitle">Welcome</div>
<div class="tooltip">Contact Us
<span class="tooltiptext">
<b>Address:</b> Central Department Of Physics, Kirtipur<br>
<b>Phone:</b> 01-4331054
</span>
</div>
<div class="logoutLink">Logout</div>
</div>
<!--LEFT BAR SECTION-->
<div class="leftSection">
<?php include("leftSection.php");?>
</div>
<!--LEFT BAR SECTION-->
<!--CONTENT AREA SECTION-->
<div class="contentSection">
<?php
// CODE FOR PERFORMMING ACTIVITY..
$activity = $_REQUEST['activity'];
if($activity) {
if(isset($_POST['activity'])) {
include("dashboard.php");
}
if($activity) {
if($activity == 'addMember'){
include("addMember.php");
}
if($activity == 'dashboard'){
include("dashboard.php");
}
if($activity == 'issueBooks'){
include("issueBooks.php");
}
if($activity == 'returnBooks'){
include("returnBooks.php");
}
if($activity == 'updateBook'){
$uBookId = $_REQUEST['uBookId'];
$return = mysql_num_rows(mysql_query("SELECT bookId From borrow Where bookId = '$uBookId'"));
if(empty($return)){
$query = mysql_query("SELECT bookId,title,author,price,publisher From books Where bookId = '$uBookId'");
$result = mysql_fetch_assoc($query);
?>
</div>
<!--CONTENT AREA SECTION-->
<!--RIGHT AREA SECTION-->
<div class="rightSection">
<?php include("rightSection.php");?>
</div>
<!--RIGHT AREA SECTION-->
</div>
<!--CONTAINER AREA SECTION-->
</body>
</html>
Change code below
<?php
// CODE FOR PERFORMMING ACTIVITY..
$activity = $_REQUEST['activity'];
if(isset($activity) || empty($activity)) {
include("dashboard.php");
}
else {
if($activity == 'addMember'){
include("addMember.php");
.............your code............
My advice is DO NOT USE $_REQUEST use $_GET, $_POST instead.
I am continuosly getting this error:
Commands out of sync; you can't run this command now
I don't know why is this happening and none of the preivous questions are helping.
This is my code:
User.php
public static function GetUserFullName($username){
if(Utilities::IsValid($username)){
$username = Utilities::SafeString($username);
Database::OpenConnection();
$query = Database::$databaseConnection->prepare("SELECT Name FROM user WHERE Username = ?") or die(Database::$databaseConnection->error);
$query->bind_param("s", $username);
$result = $query->execute();
Database::CloseConnection();
if($result){
$query->bind_result($name);
$query->fetch();
$query->close();
return $name;
}
}else return -1;
}
Skill.php
public static function UpdateSkills($id, $skill, $action){
if(Utilities::IsValid($id) && Utilities::IsValid($skill) && Utilities::IsValid($action)){
$id = Utilities::SafeString($id);
$skill = Utilities::SafeString($skill);
$action = Utilities::SafeString($action);
Database::OpenConnection();
if($action == 'i'){
$skill = str_replace(" ", "", $skill);
$db = Database::$databaseConnection;
$skills = explode(",", $skill);
$query = "";
foreach ($skills as $s){
$query .= "INSERT INTO skill (User_ID,Skill) VALUES({$id},'{$s}');";
}
$result = $db->multi_query($query);
echo $db->error;
Database::CloseConnection();
if($result) return 1;
else return -1;
}else if($action == 'd'){
$query = Database::$databaseConnection->prepare("DELETE FROM Skill WHERE Skill = ? AND User_ID = ?");
$query->bind_param("si", $skill,$id);
$result = $query->execute();
Database::CloseConnection();
if($result && $query->num_rows >0) return 1;
else return -1;
}
}
return -1;
}
header.php
<?php
require_once 'Classes/UserLogin.php';
require_once 'Classes/User.php';
$user_fullname = User::GetUserFullName($_SESSION["username"]);
?>
<header>
<div class="welcome_area">
<p>
Welcome, <b><?php echo $user_fullname; ?> </b>
</p>
</div>
<div class="menu">
<nav>
<ul>
<li>My Profile
<ul>
<li><div>My Questions</div>
</li>
<li><div>Settings</div>
</li>
<li style="margin-bottom: 5px;"><div>Logout</div>
</li>
</ul>
</li>
<li>Inbox
</li>
<li>Notifications
</li>
</ul>
</nav>
</div>
</header>
<section id="container">
<br />
<div id="logo"></div>
<div id="content">
profile.php
<?php
require_once "Classes/User.php";
require_once "Classes/Skill.php";
require_once "Classes/UserLogin.php";
if(!UserLogin::IsLoggedIn("username")) header("location: login.php");
$user_details = User::GetUserDetails($_SESSION["username"]);
echo Skill::UpdateSkills(11, "programmer,designer", "i");
?>
<!DOCTYPE html>
<html>
<head>
<title>Help Exchange</title>
<link rel="stylesheet" href="css/base.css" />
<link rel="stylesheet" href="css/profile.css" />
<link rel="stylesheet" href="css/user.css" />
<link rel="stylesheet" href="css/widgets.css" />
<script src="js/jquery.min.js"></script>
<script src="js/profile.js"></script>
</head>
<body>
<script>
var user_details = eval(<?php echo $user_details; ?>);
var about = user_details.About;
</script>
<?php require_once 'admin/header.php';?>
Please help me :'(