I am trying to create a shopping cart with PHP, but, once the user leaves the cart area, all of the products disappear. That's what I'm trying to do:
<?php foreach($almofadas as $almofadas):?>
<form action="cart.php" method="GET">
<div class="base col-6 col-sm-4 col-md-5 col-lg-4 col-xl-4">
<div class="card">
<img src="uploads/<?php echo $almofadas['imagem']; ?>" alt="">
<div class="content-c">
<div class="row-p">
<div class="details">
<span><?php echo $almofadas['pnome'] ; ?></span>
</div>
<div class="price">R$ <?php echo $almofadas['preço'];?> </div>
</div>
<input type="hidden" name="id" value="<?php echo $almofadas['p_id']?>">
<div style="margin-top: 10px;">
<div style="margin-bottom: 5px;"><button class="buttons-1" data-toggle="modal" data-target="#myModal">Detalhes</button></div>
<div><button class="buttons-2" type="submit">Adicionar ao Carrinho</a> </button></div>
</div>
</div>
</div>
</div>
</form>
<?php endforeach; ?>
Now the cart system:
<?php
session_start();
require_once 'conn.php';
$_SESSION['id'] = $_GET['id'];
$result_pedido = "SELECT * FROM tb_produtos WHERE p_id = '{$_SESSION['id']}'";
$resultado_pedido = mysqli_query($conn, $result_pedido);
$pedidos = mysqli_fetch_all($resultado_pedido, MYSQLI_ASSOC);
?>
Here I can only add one product and, I can't save it into a $_SESSION, having said that the product disapears once iI leave the cart.
<?php foreach($pedidos as $pedidos):?>
<tr>
<td>
<div class="cart-img">
<img src="uploads/<?php echo $pedidos['imagem'];?>" width="125px">
</div>
</td>
<td>
<div class="cart-model">
<?php echo $pedidos['pnome'] ; ?>
</div>
</td>
<td>
<div class="cart-quantity">
<input class="i-quantity" type="number" value="1">
</div>
</td>
<td>
<div class="cart-price">
R$<?php echo $pedidos['preço'] ; ?>
</div>
</td>
</tr>
</tbody>
</table>
<?php endforeach; ?>
If you check this line:
$_SESSION['id'] = $_GET['id'];
This mean the "id" in your $_SESSION is always set to $_GET['id'], even if it is empty. So it is reset every time the user visit a page.
You should:
have some mechanism to store your shopping cart content. There is none in your code; and
have a way to check if the user visits a new id before storing it to shopping cart.
For example,
<?php
/**
* This only make sense if this script is called
* by some AJAX / javascript interaction to specifically
* add a new item to cart.
*/
session_start();
require_once 'conn.php';
if (isset($_GET['id']) && !empty($_GET['id'])) {
$_SESSION['id'] = $_GET['id'];
}
$result_pedido = "SELECT * FROM tb_produtos WHERE p_id = '{$_SESSION['id']}'";
$resultado_pedido = mysqli_query($conn, $result_pedido);
$pedidos = mysqli_fetch_all($resultado_pedido, MYSQLI_ASSOC);
// If the user visits a path where the $_GET['id'] have result in
// database and the user specified that he / she want to save something
// to his / her cart.
if (isset($_GET['id']) && !empty($_GET['id']) && !empty($pedidos)) {
if (!isset($_SESSION['cart'])) $_SESSION['cart'] = []; // initialize if not exists.
$_SESSION['cart'] = array_merge($_SESSION['cart'], $pedidos);
}
?>
Note: the quantity should be set to the cart somehow. You need to change the data structure to set or increment the "qty". But this is at least a start.
Related
I am trying to create a simple cart system for my online shop. In order to store add the items the user selects to the cart, I have created an add to cart button under my items. My goal is that when this button is pressed the uid that is saved in my database, of the item selected is saved on a current session. However, when I press this button, for some reason it is always the id of the third item (cabuid 3) that gets saved onto the session, regardless of which item I add to cart.
Here is my database
index.php file
<form style="border:1px solid #ccc" method="POST" enctype="multipart/form-data">
<?php
if (isset($_POST['add'])){
print_r($_POST['product_id']);
}
include __DIR__.'../includes/dbh.includes.php';
$sql = "SELECT * FROM boots";
$gotResults = mysqli_query($connection,$sql);
if($gotResults) {
if(mysqli_num_rows($gotResults)>0) {
while($row = mysqli_fetch_array($gotResults)){
?>
<div class="row">
<div class="column">
<div class="card">
<img src="images/<?php echo $row['image']?>" style="width:100%">
<div class="container">
<h2>
<?php echo $row['cabname']; ?> </h2>
<p><?php echo $row['cabdescription']; ?></p>
<p><?php echo $row['cabprice']; ?> € </p>
<p><button type="submit" class="button" name="add">Add to cart</button></p>
<input type='hidden' name='product_id' value="<?php echo $row['cabuid']; ?>">
</div>
</div>
</div>
<?php
}
}
}
?>
dbh.includes.php
<?php
$serverName = "localhost";
$dbUsername ="root";
$dbPassword ="";
$dbName = "webvacser";
$connection = mysqli_connect($serverName, $dbUsername, $dbPassword, $dbName);
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
?>
I would make `n` forms, one per iteration of the loop
<?php
include __DIR__.'../includes/dbh.includes.php';
$sql = "SELECT * FROM boots";
$gotResults = mysqli_query($connection,$sql);
if($gotResults) {
if(mysqli_num_rows($gotResults)>0) {
while($row = mysqli_fetch_array($gotResults)){
?>
<div class="row">
<div class="column">
<div class="card">
<img src="images/<?php echo $row['image']?>" style="width:100%">
<div class="container">
<h2> <?php echo $row['cabname']; ?> </h2>
<p><?php echo $row['cabdescription']; ?></p>
<p><?php echo $row['cabprice']; ?> € </p>
<form style="border:1px solid #ccc" method="POST" enctype="multipart/form-data">
<p><button type="submit" class="button" name="add">Add to cart</button></p>
<input type='hidden' name='product_id' value="<?php echo $row['cabuid']; ?>">
</form>
</div>
</div>
</div>
<?php
}
}
}
?>
Now the 3 forms are unique and when you press the button inside any one of them the correct data from the associated hidden input will be sent to the receiving script
Displaying posts by specific user? this i saw is for ruby on rails and it couldn't help me..
I have two tables, users and posts.
If a user posts anything, it displays on his dashboard which works fine for now. But what i need is for the user to view only his posts.
Please help...
Below is my code:
server.php
<?php
// connect to database
require_once 'database.php';
// initialize variables
$note = "";
$id = 0;
$edit_state = false;
// if save button is clicked
if (isset($_POST['save'])) {
$note = addslashes($_POST['note']);
$created_at = date("Y-m-d H:i:s");
// basic first name validation
if (empty($note)) {
$error = true;
$noteError = "Field cannot be empty.";
}else {
// insert records if no error
$query = "INSERT INTO posts (note, created_at, updated_at) VALUES ('$note', '$created_at', NOW())";
mysqli_query($dbconn, $query);
$_SESSION['msg'] = "Saved";
header('location: ../home.php'); // redirect to home page after inserting
}
}
?>
and this is home.php where results are displayed
<?php
ob_start();
session_start();
error_reporting(E_ALL);
require_once 'config/database.php';
include 'config/server.php';
// if session is not set this will redirect to login page
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
// select loggedin users detail
$res=mysqli_query($dbconn, "SELECT * FROM users WHERE Id=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
?>
<div class="container" style="margin-top: 100px;">
<div class="row">
<div class="col-sm-6">
<div class="wrap-status100">
<form method="post" class="login100-form validate-form" action="config/server.php" autocomplete="off">
<span class="login100-form-title p-b-26">
<?php if (isset($_SESSION['msg'])): ?>
<div class="form-group">
<div class="alert alert-<?php echo $_SESSION['msg']; unset($_SESSION['msg']); ?>">
<span class="glyphicon glypicon-info-sign"></span>
</div>
</div>
<?php endif ?>
What's up <?php echo $userRow['fname']; ?>?
</span>
<div class="wrap-input100 validate-input">
<textarea name="note" class="input100" value="<?php echo $note; ?>"></textarea>
<span class="focus-input100" data-placeholder="Write note here."></span>
</div>
<div class="container-login100-form-btn">
<div class="wrap-login100-form-btn">
<div class="login100-form-bgbtn"></div>
<?php if ($edit_state == false): ?>
<button name="save" class="login100-form-btn">
Save
</button>
<?php else: ?>
<button name="update" class="login100-form-btn">
Update
</button>
<?php endif ?>
</div>
</div>
</div>
</form>
</div>
<div class="col-sm-6">
<?php if (isset($_SESSION['msg'])): ?>
<div class="msg">
<?php
echo $_SESSION['msg'];
unset($_SESSION['msg']);
?>
</div>
<?php endif ?>
<table>
<thead>
<tr>
<th>Note</th>
<th>created</th>
<th>Updated</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['note']; ?></td>
<td><?php echo $row['created_at']; ?></td>
<td><?php echo $row['updated_at']; ?></td>
<td><a class="edit_btn" href="home.php?update=<?php echo $row['id']; ?>">Update</a>
</td>
<td>
<a class="del_btn" href="config/server.php?del=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
You need to take one more column in posts table i.e user_id. You have to store the id of user who create the Post.
While fetching the result, you can take logged in user's id. And create a query like
"Select * from posts where user_id=".$_SESSION['user'];
by this you have get all the posts created by that particular user.
Hope this helps.
Thanks.
You need to do this in this way:
First while adding a post you have to insert the user id of the user who is posting the post. Be sure to add a field named user_id in the posts table in db. PLease try this query:
$user_id=trim($_SESSION['user']);
$query = "INSERT INTO posts (note,user_id, created_at, updated_at) VALUES ('$note', '".$user_id."' , '$created_at', NOW())";
Now in the dashboard of the user you need to fetch the posts based on the user_id and then loop the tr in the results array:
"Select * from posts where user_id=".$_SESSION['user'];
$name=$_SESSION['name'];
$q="select * from purchase where name='$name'";
$qs=mysqli_query($con,$q);
while($r=mysqli_fetch_array($qs))
{
?>
<div class="col-md-2">
<img src="<?php echo $r['p_img'];?>" width="200px" height="200px">
</div>
<div class="col-md-4">
<label>Product Name:</label><?php echo $r['p_name']; ?>
<div>
<label>Cost:</label><?php echo $r['p_cost'];?>
</div>
<div>
<label>Quntity:</label><?php echo $r['p_qun'];?>
</div>
<label>Product Detailes:</label><?php $arr=explode(".",$r['p_detailes']);
foreach($arr as $a)
{
echo $a;?><br><?php
}
?>
</div>
<?php
}
?>
</div>
this is my purchase.php page
i have created purchase.php page and showed the customer purchases detailes but now i want to delete the detailes when customer logout.
Just run UPDATE SQL:
$q="UPDATE purchase SET detailes='' where name='$name'";
please help. I am building a website where people can upload their projects. I designed it in such a way that one person can have multiple projects. I am fairly new to php and I know I posted way too much code but I need help
I have been able to make the project titles for each user show dynamically when they login in. The problem I have is how do I make each link load up the page with the full project details. Right now it only shows the first project details no matter what title is clicked. Below is the profile page.
<?php if(isset($login_projectTittle)){
echo "Click to see your projects";
?>
<br><br><br><br><br>
<?php
$query = "SELECT * FROM fullprojectdetails WHERE user_id=$login_id";
if ($result=mysqli_query($connection,$query)){
if($count = mysqli_num_rows($result)){
/* because of the mysqli_fetch_object function the variables have to be $rowe->title (as an object) */
while($rowe = mysqli_fetch_object($result)){
?>
<?php $_SESSION['projectstuff'] = $rowe ->projecttitle; ?>
<?php $_SESSION['projectIdNew'] = $rowe ->projectid; ?>
<?php echo $rowe ->projecttitle; ?>
<br>
<?php
}
/* mysqli_free_result frees p the result in the variable ths allowing for a new one each time */
mysqli_free_result($result);
}
}
}
else {echo "";}
?>
I used POST to send the data to the database.
The page that should load up the full project details is the project page. Contents to be displayed on this page are drawn from the session code which is included in the project page and displayed below
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
require('databaseConnect.php');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Selecting Database
require('databaseSelect.php');
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User (MYSQL Inner Join used here) took hours to learn
$ses_sql=mysqli_query($connection, "select user.user_emailaddress, user.user_fullname, user.user_id, fullprojectdetails.fileToUpload, fullprojectdetails.projecttitle,
fullprojectdetails.projectcreated, fullprojectdetails.projectcategory, fullprojectdetails.projectcountry, fullprojectdetails.projectdetails,
fullprojectdetails.fundTime, fullprojectdetails.fundinggoal, fullprojectdetails.fileToUpload2, fullprojectdetails.name, fullprojectdetails.biography,
fullprojectdetails.yourlocation, fullprojectdetails.website, fullprojectdetails.fileToUpload3, fullprojectdetails.projectdetails2, fullprojectdetails.accountName, fullprojectdetails.bankName, fullprojectdetails.accountType,
fullprojectdetails.accountNo,fullprojectdetails.user_id, fullprojectdetails.projectid from user inner join fullprojectdetails on user.user_id=fullprojectdetails.user_id where user.user_emailaddress='$user_check'");
//saving variables to be used in every page with session_new included
$row = mysqli_fetch_assoc($ses_sql);
$login_session =$row['user_emailaddress'];
$login_fullname =$row['user_fullname'];
$login_id =$row['user_id'];
$login_projectTittle = $row['projecttitle'];
$login_projectLocation = $row['yourlocation'];
$login_projectCategory = $row['projectcategory'];
$login_projectFundGoal = $row['fundinggoal'];
$login_projectSummary = $row['projectdetails'];
$login_projectWebsite = $row['website'];
$login_projectVideo = $row['fileToUpload3'];
$login_Pic = $row['fileToUpload2'];
$login_projectID = $row['projectid'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectFullDet = $row['projectdetails2'];
if(!isset($login_session)){
mysqli_close($connection); // Closing Connection
header('Location: login.php'); // Redirecting To Home Page
}
?>
Below is the project page code
<?php
include('session_new.php');
/*echo $_SESSION['projectstuff'];
if (isset($_POST['profile_btn'])){*/
/* if (isset ($_SESSION['projectstuff'])){
$ses_sql=mysqli_query($connection, "select * from fullproject where projecttitle='{$_SESSION['projectstuff']}");*/
?>
<!DOCTYPE html>
<html>
<body>
<!--require for the nav var-->
<?php require 'logged-in-nav-bar.php';?>
<div id= "upperbodyproject">
<div id= "projectheader">
<h2> <?php echo $login_projectTittle; ?><h2>
</div>
<!-- video and funder div-->
<div id = "vidFundCont">
<div id = "video">
<video width='100%' height='100%' controls> <source src="<?php echo $login_projectVideo ?>" type='video/mp4'>Your browser does not support the video tag.</source></video>
</div>
<div id = "funders">
<p> <strong> 20 </strong> <br> <br><span>funders </span> </p> <br> <br> <br>
<p> </p><br>
<p> <span>funded of N<?php echo $login_projectFundGoal ; ?> </span><p><br> <br> <br>
<p><strong> 15 </strong> <br> <span> <br> days left </span></p><br> <br> <br>
<button id = "projectPageButton"> Fund This Project </button>
</div>
<div id = "clearer"></div>
</div>
<!-- location and project condition -->
<div id = "location">
<p> Location: <?php echo $login_projectLocation ; ?> Category:<?php echo $login_projectCategory ; ?> </p>
</div>
<div id ="projectconditions">
<p> This project will only be funded if N<?php echo $login_projectFundGoal ; ?> is funded before the project deadline</p>
</div>
<div id = "clearer"> </div>
<!--project summary and profile -->
<div id = "nutshell">
<p><?php echo $login_projectSummary ; ?> </p> <br> <br>
<span>Share:</span>                            
             
             
</div>
<div id = "projProfile">
<div id = "projProfileTop">
<img src="<?php echo $login_Pic ; ?>" width = "50%" height = "100%">
</div>
<div id ="projProfileBottom">
<br>
<p id = "profileNameStyle"> Name: <?php echo $login_fullname; ?> </p> <br>
<p> Website: <?php echo $login_projectWebsite ; ?> </p> <br>
<p> Email: <?php echo $login_session; ?> </p>
</div>
</div>
<div id = "clearer"> </div>
<!-- about and reward title -->
<div id = "aboutProjH">
<h2> About This Project </h2>
</div>
<div id = "rewardH">
<h2> Rewards For Supporting This Project</h2>
</div>
<div id = "clearer"> </div>
<!--project pic and dynamic rewards-->
<div id = "projPic">
<img src="<?php echo $login_projectPic;?>" width = "100%" height = "100%">
</div>
<div id = "rewardDet">
<br>
<span><?php echo $login_projectFullDet; ?> </span>
</div>
<div id = "clearer"> </div>
<div id = "clearer"> </div>
<!-- project details and empty divs -->
<?php
// code to select content form database and display dynamically in a div
$query = "SELECT * FROM reward WHERE user_id=$login_id";
if ($result=mysqli_query($connection,$query)){
if($count = mysqli_num_rows($result)){
/* because of the mysqli_fetch_object function the variables have to be $rowe->title (as an object) */
while($rowe = mysqli_fetch_object($result)){
?>
<div id = "projDet">
<p> <h2><?php echo "N".$rowe->pledgeAmount. " " . "or more"; ?></h2></p> <br>
<p><span> <br><?php echo $rowe ->title; ?></span></p> <br>
<p> <span><?php echo $rowe ->description; ?></span></p> <br>
<p> <span>Estimated Delivery Time: <br> <?php echo $rowe ->deliverytime . " ". $rowe ->deliveryyear; ?></span></p> <br>
<p> <span><?php echo $rowe ->shippingdetails; ?></p></span> <br>
<p> <span>Number of Rewards Available: <br><?php echo $rowe ->reward1No; ?></span></p>
</div>
<!--<div id = "bsideProjDet">
</div> -->
<div id = "clearer"> </div>
<?php
}
/* mysqli_free_result frees p the result in the variable ths allowing for a new one each time */
mysqli_free_result($result);
}
}
/* display dynamic form */
/*$s_sql=mysqli_query($connection, "SELECT * FROM reward WHERE user_id=$login_id");
$rowe = mysqli_fetch_assoc($s_sql);
?>
<?php echo $rowe['title']; ?><br><br>
<?php echo $rowe['pledgeAmount']; ?><br><br>
<?php echo $rowe['description']; ?><br><br>
<?php echo $rowe['deliverytime']; ?><br><br>
<?php echo $rowe['deliveryyear']; ?><br><br>
<?php echo $rowe['shippingdetails']; ?><br><br>
<?php echo $rowe['reward1No']; ?><br><br> */
?>
<div id = "reportProj">
<button id = "projectPageButton"> Report This Project To Gbedion</button>
</div>
<!--<div id = "bsideReportProj"> </div>-->
<div id = "clearer"> </div>
<!-- </div> -->
</div>
<?php
/*}
}
else {
echo "Select a project";
}*/
?>
<!-- page footer-->
<?php require 'logged-in-footer.php';?>
</body>
</html>
The project Id is the primary key and user id is the foreign key in fullprojectdetails table. If more database details are needed please let me know. Had to abandon this project for a month because of this problem.
First don't store the projectid and project title on a session variable, on the profile page, just create a normal variable and store them on that variable, then when you linking to project.php create a query strings, with the id of the project then with the title of the project, ie Dynamic Project Title I believe when you store the id's of the projects in a session, once you click on one project, the browser will always use that id no matter which project you click next, until you unset/destroy the sessions(logout).
there fore this on profile :
<?php $_SESSION['projectstuff'] = $rowe ->projecttitle;?>
<?php $_SESSION['projectIdNew'] = $rowe ->projectid; ?>
<?php echo $rowe ->projecttitle; ?>
should change to :
<?php $projectstuff = $rowe ->projecttitle; ?>
<?php $projectIdNew = $rowe ->projectid; ?>
<?php echo $rowe ->projecttitle; ?>
Then on projetc.php
you first check if the id isset and also the title, then do your queries
this is how you would do it
project.php
<?php
session_start();
//validate your sessions
if (isset($_GET['projectid']) && isset($_GET['projecttitle'])) {
$currentProjectID = urldecode(base64_decode($_GET['projectid']));
$projectTitle = $_GET['projecttitle'];
?>
<?php
require 'logged-in-nav-bar.php';
?>
<div id= "upperbodyproject">
<div id= "projectheader">
<h2> <?php echo $projectTitle; //from the query string ?></h2>
</div>
<!-- get the details of this project -->
<?php
$query = "SELECT * FROM fullprojectdetails WHERE projectid=$currentProjectID";
// Continue your staff then
?>
</div><!-- upperbodyproject -->
<?php
} else {
echo "could not find project id";
}
?>
Hope this will help point you to the correct direction, I would suggest that you look at mysqli prepared statements, and also at PDO prepared statements.
I am working on this product page. Basically it shows a product by ID and gives you the option to add it to your cart. My problem is that the data stored in $_SESSION gets lost every time I refresh the page.
<?php
include 'scripts\init.php'; // contains session_start(); and the functions
if(!IsProductIdSafeAndExisting())
{
session_write_close();
header("Location: shop.php");
die();
}
if(isset($_POST['quantity'])) // adds current item to cart but gets lost after refresh
AddItemToCart($_GET["id"],$_POST['quantity']);
$id = $_GET["id"];
$name = GetProductField($id,"name");
$image = GetProductField($id,"image");
$price = GetProductField($id,"price");
$stock = GetProductField($id,"stock");
$details = GetProductField($id,"details");
$total_products = GetTotalProducts();
$total_price = GetTotalProductsPrice();
LoadHeaderByTitle($name." | Magazin Vinuri");
?>
<body>
<div id="page">
<?php LoadNavigationBy(""); ?>
<div id="body">
<div class="header">
<div>
<h1><?php echo $name; ?></h1>
</div>
</div>
<div class="singlepost">
<div class="featured">
<img src="images/<?php echo $image; ?>" alt="">
<h1><?php echo $name.' - '.$price.' lei'; ?></h1>
<span>Mai sunt <?php echo '<strong>'.$stock.'</strong>'; ?> bucati ramase.</span>
<p><?php echo $details; ?></p>
<div class="additem">
<center>
<form method="POST" action="product.php?id=<?php echo $id; ?>">
<input type="text" name="quantity" value="Cantitate" onblur="this.value=!this.value?'Cantitate':this.value;" onfocus="this.select()" onclick="this.value='';">
<input type="submit" value="Adauga" id="submit">
</form>
</center>
</div>
</div>
<div class="sidebar">
<h1>Cosul tau</h1>
<img src="images/cart.png" alt="">
<h2><?php echo $total_price; ?> lei</h2><br>
<p>Momentan aveti <strong><?php echo $total_products; ?></strong> produse in cos. Pentru a edita lista de produse dati click pe butonul de mai jos.</p>
vezi cumparaturi
</div>
</div>
</div>
<?php include 'scripts\overall\foot.php' ?>
init.php
<?php
session_start();
require 'database\connect.php';
require 'functions\general.php';
require 'functions\engine.php';
?>
the problem was that I stored product ids like this $_SESSION[10]=something; which was wrong because it the same as $_SESSION['10']=something; so i changed it to $_SESSION['id_10']=something; and now it works