I am practicing with PHP, and as a result, I ended up creating a dummy online store. I managed to implement most of the online functionality, but I am struggling with the shopping cart.
Once the user logs in and enters the product area of the site, I want the user to be able to add items to a cart. I have been following a phpAcademy YouTube tutorial. I've managed to display all the products with an add button/hyperlink to link each product to a processing page called cart.php. Each button's link matches their associated product ID.
When I test this and click "add", the ID of the product does not appear on the cart.php page.
user_man_boxing_gloves.php:
<?php
session_start();
include('connect_mysql.php');
$product_name = 'product_name';
$product_qua = 'product_qua';
$product_price = 'product_price';
$product_image = 'product_image';
$product_des = 'product_des';
$get = mysql_query("SELECT product_id, product_image, product_name, product_des, product_price, product_type FROM products WHERE product_type='ManGloves' AND product_qua > 0 ORDER BY product_id DESC");
if(mysql_num_rows($get) == 0)
{
echo "There are no Products to display";
}
else
{
?>
<?php
while($get_row = mysql_fetch_assoc($get))
{
?>
<table id='display'>
<tr><td><?php echo "<img src=$get_row[$product_image] class='grow'>" ?></td></tr>
<tr>
<th></th>
<th><strong>Avalible</strong></th>
<th><strong>Price</strong></th>
<th><strong>Description</strong></th>
</tr>
<tr>
<td width='290px'><?php echo "$get_row[$product_name]" ?></td>
<td width='290px'><?php echo "$get_row[$product_qua]" ?></td>
<td width='290px'><?php echo "$get_row[$product_price]" ?></td>
<td width='290px'><?php echo "$get_row[$product_des]" ?></td>
</tr>
<tr>
<td><?php echo 'Add'; ?></td>
</tr>
</table>
<?php
}
}
?>
cart.php:
<?php
if(isset($_GET['add'])){
$_SESSION['cart_'.$_GET['add']]+='1';
}
echo $_SESSION['cart_'];
?>
I want to display the product ID to see if my code works, and I want to do further processing after verifying that it works.
Looking at the screenshot, it appears that the add button correctly shows the product ID.
It looks like the issue in cart.php deals with the following snippet:
if(isset($_GET['add'])){
$_SESSION['cart_'.$_GET['add']]+='1';
}
Working this out, this would mean that with an ID of 1, you could see the following in your session array:
$_SESSION['cart_1'] = 1;
$_SESSION['cart_2'] = 4;
What you probably want, for the display, is to store an array into cart. That is,
if(isset($_SESSION['cart']))
{
$arr = unserialize($_SESSION['cart']);
}
else
{
$arr = array();
}
if(isset($_GET['add'])){
$arr[$_GET['add']] += 1;
}
$_SESSION['cart'] = serialize($arr);
var_dump(unserialize($_SESSION['cart']));
Related
So I have this food ordering system where each admin uploads his or her food from the backend and users can browse through those food from the frontend, a simple program. But what I want is that an admin should not be able to view or update the food from another admin as right now any of the admins can view and update all the food that are uploaded on the backend. What I want is only a specific admin only viewing and updating his or her added food items.
Attached below is the snippet and picture of the food view and update page where it displays all foods and can update them.
FYI the code is in PHP and the backend is SQL in phpMyAdmin
Please do let me if there are any confusions in my explanation.
<?php include('partials/menu.php'); ?>
<div class="main-content">
<div class="wrapper">
<h1>Manage Food</h1>
<br /><br />
<!-- Button to Add Admin -->
Add Food
<br /><br /><br />
<?php
if(isset($_SESSION['add']))
{
echo $_SESSION['add'];
unset($_SESSION['add']);
}
if(isset($_SESSION['delete']))
{
echo $_SESSION['delete'];
unset($_SESSION['delete']);
}
if(isset($_SESSION['upload']))
{
echo $_SESSION['upload'];
unset($_SESSION['upload']);
}
if(isset($_SESSION['unauthorize']))
{
echo $_SESSION['unauthorize'];
unset($_SESSION['unauthorize']);
}
if(isset($_SESSION['update']))
{
echo $_SESSION['update'];
unset($_SESSION['update']);
}
?>
<table class="tbl-full">
<tr>
<th>S.N.</th>
<th>Title</th>
<th>Price</th>
<th>Image</th>
<th>Featured</th>
<th>Active</th>
<th>Actions</th>
</tr>
<?php
//Create a SQL Query to Get all the Food
$sql = "SELECT * FROM tbl_food";
//Execute the qUery
$res = mysqli_query($conn, $sql);
//Count Rows to check whether we have foods or not
$count = mysqli_num_rows($res);
//Create Serial Number VAriable and Set Default VAlue as 1
$sn=1;
if($count>0)
{
//We have food in Database
//Get the Foods from Database and Display
while($row=mysqli_fetch_assoc($res))
{
//get the values from individual columns
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$image_name = $row['image_name'];
$featured = $row['featured'];
$active = $row['active'];
?>
<tr>
<td><?php echo $sn++; ?>. </td>
<td><?php echo $title; ?></td>
<td>$<?php echo $price; ?></td>
<td>
<?php
//CHeck whether we have image or not
if($image_name=="")
{
//WE do not have image, DIslpay Error Message
echo "<div class='error'>Image not Added.</div>";
}
else
{
//WE Have Image, Display Image
?>
<img src="<?php echo SITEURL; ?>images/food/<?php echo $image_name; ?>" width="100px">
<?php
}
?>
</td>
<td><?php echo $featured; ?></td>
<td><?php echo $active; ?></td>
<td>
Update Food
Delete Food
</td>
</tr>
<?php
}
}
else
{
//Food not Added in Database
echo "<tr> <td colspan='7' class='error'> Food not Added Yet. </td> </tr>";
}
?>
</table>
</div>
</div>
<?php include('partials/footer.php'); ?>
Attached is a picture of this
What you need is a new column in the table tbl_food
Actual clumns:
//get the values from individual columns
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$image_name = $row['image_name'];
$featured = $row['featured'];
$active = $row['active'];
Add a column "owned_by" with the admin_ID of the user that added that food.
Step 1. (that's MySQL, but you can adapt to your DB)
alter table tbl_food add owned_by int;
Step 2.
when some admin add a food, you add this ID value in the insert, with others food information.
Step 3.
When some admin update the food, you check if this food is owned by this admin, and in update query you add
[..]and owned_by = admin_ID;
To accomplish this, you need that any admin has his own ID or email or access token
If all the admins are sharing the same account to upload the food, before of what I said you need to add a multiuser control access system.
I have around 5 meal category, for example 'M01' ('M' stands for Meal), 'B01' ('B' stands for Baverages) and so on. In every category page on front end, instead of showing everything in 1 page, I want to sort the product based on its category, for example in Baverages page, there will be a list of baverages under 'B01' category code. How can I achieve that with PHP and MySQLi? Sorry for the simple code, I'm still new to this. Thanks in advance!
Here's my code:
<table class="table-list">
<tbody id="mealTable">
<?php
$result=mysqli_query($conn,"SELECT * FROM meal");
$row_count = mysqli_num_rows($result);
if ($row_count == 0) { ?>
<tr>
<td colspan = "6">
<?php echo "No data found"; ?>
</td>
</tr>
<?php } else {
while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $row['meal_name']?></td>
<td>RM <?php echo $row['meal_price']?></td>
<td >Add To Cart
</td>
</tr>
<?php } }
?>
</div>
This is the List of Meal page on Admin side
This is the database table for Meal Category
This is the database table for Meal
I'll try to explain the problem straight away. I have one HTML form which takes input just like a comment form and it saves the xyz data into a MySQL database using PHP. Now, what I want is to create and display links for those comments on a page.
I mean the comments which have been saved including the user's email and name, should be opened by clicking a link.
I don't want to display all the details on a single page from the database for all the users. There should be a page on which links are shown, when a user click a link, the full post should be displayed in next page.
There is not something which I know about this process. Please help me out.
// $rows = set of result from your database query
foreach($rows as $row){
echo '<a'
. ' href="my_link_to_display_comment?id='.$row['id'].'">'
. 'Comment from '.$row['user_name']
. '</a>';
}
First a page to display all the links like the below example -
$result = mysql_query("SELECT * FROM calendar WHERE sort_month='11'");
while($row = mysql_fetch_array($result))
{echo
"".$row['event_name'].""
;}
and then in event.php(the next page after clicking link)
$id = $_GET['id'];
$sql = "select * from calendar where id = $id";
$result = mysql_query($sql, $con);
if ($result){
$row = mysql_fetch_row($result);
$title = $row[12];
$content = $row[7];} ?>
<?php echo $title ?>
<?php echo $content ?>
If you want to show details of a single user just do this.
You can make a search box by using a form.
eg. like if I want to display a details of a student, I will search him by using his roll number and run these queries.
<?php //to search student
require_once './secure.inc.php';
$status = 0;
if(isset($_POST['submit'])){
$roll_number = $_POST['roll_number'];
$query = "select * from students where roll_number=$role_number";
require_once '../includes/db.inc.php';
$result = mysql_query($query);
if(mysql_num_rows($result)==1){
$status = 1;
$row = mysql_fetch_assoc($result); //mysql_fetch_array - both numeric and key index
}else{
$status=2;
}
}
?>
//to display
<?php } else if($status==1) { ?>
<table>
<tbody>
<tr>
<td>Roll Number : </td>
<td><?php echo $row['roll_number']; ?></td>
</tr>
<tr>
<td>Name : </td>
<td><?php echo $row['name']; ?></td>
</tr>
<tr>
<td>Gender : </td>
<td><?php echo $row['gender']; ?></td>
</tr>
<tr>
<td>Email : </td>
<td><?php echo $row['email']; ?></td>
</tr>
<tr>
<td>Mobile Number : </td>
<td><?php echo $row['mobile_number']; ?></td>
</tr>
<tr>
<td>Course : </td>
<td><?php echo $row['course']; ?></td>
</tr>
</tbody>
</table>
<?php } ?>
I am working on a basic ecommerce website using PHP/MYSQL. I just need to know how I can upload multiple images for a product and then display them in the products page.
as for uploading multiple images, I don't want to use uploadify or open source codes like that. i rather have 3-4 extra fileupload fields if possible at all!
And I cannot get my head around the displaying the images (multiple images for 1 product). I really don't understand how it should work! so any advice on simple terms would be appreciated.
Currently I can only upload 1 image per product.
Here is what I have so far, please ignore the mysql queries in the first file as this is a not going live yet until I have converted the mysql to mysqli. Just need to get functions sorted first:
upload.php
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['product_name'])) {
$product_name = mysql_real_escape_string($_POST['product_name']);
$price = mysql_real_escape_string($_POST['price']);
$quantity = mysql_real_escape_string($_POST['quantity']);
$category = mysql_real_escape_string($_POST['category']);
$details = mysql_real_escape_string($_POST['details']);
// See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT id FROM products WHERE product_name='$product_name' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
// Add this product into the database now
$sql = mysql_query("INSERT INTO products (product_name, price, quantity, details, category, date_added)
VALUES('$product_name','$price','$quantity','$details','$category',now())") or die (mysql_error());
$pid = mysql_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
header("location: add.php");
exit();
}
?>
product.php <<< this is the page that displays the product details and image.
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
include "config/connect.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = "SELECT * FROM products WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$quantity = $row["quantity"];
$category = $row["category"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
<table width="900" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="300" rowspan="5" align="right" valign="top" style="padding-top:10px;"><img src="inventory_images/<?php echo $id; ?>.jpg" width="300" height="450" alt="<?php echo $product_name; ?>" /></td>
<td width="126" height="106"> </td>
<td width="274"><h3 style="font-family:Times New Roman; font-size:1.8em;"><?php echo $product_name; ?></h3></td>
</tr>
<tr>
<td height="120"> </td>
<td><?php echo $details; ?></td>
</tr>
<tr>
<td height="110"> </td>
<td style="font-family:Times New Roman; font-size:1.8em;">Price: £<?php echo $price; ?></td>
</tr>
<tr>
<td height="50"> </td>
<td style="font-family:Times New Roman; font-size:1.8em;">Quantity Left: <?php echo $quantity; ?></td>
</tr>
</table>
Thanks
Well the way you are currently doing it isn't really setup for multiple photos since you aren't storing a reference to the photo in the database. You are simply renaming the image to the primary key of the product. So you will need to either do something like 1_1.jpg 1_2.jpg or you will need to create a database table that stores the filename and the product id so you can have a one to many relationship.
As for uploading more images just add more file inputs to your form.
And for displaying you will need to either pull records from the photo db table or use glob() to find all the files that start with the primary key + '_'.
Also FYI mysql functions should no longer be used as they are deprecated.
So i edited my own shop but im having some issues with it, for example it add 2 instead of 1 or it removes 2 instead of 1,
you can see how it looks on www.neobotmx.org/test/tienda.php <<< not opwn for the public yet >> thats why its on a test folder
The shop code :
<?php
$product_id = $_GET[id]; //the product id from the URL
$action = $_GET[action]; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
if($product_id && !productExists($product_id)) {
die("Error. Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id
if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
?>
<?php
if($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" align=\"center\" padding=\"3\" width=\"70%\">";
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\"><strong>Producto</strong></td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\"><strong>Cantidad</strong></td>";
echo "<td align=\"center\"><strong>Costo</strong></td>";
echo "</tr>";//format the cart using a HTML table
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach($_SESSION['cart'] as $product_id => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT name, description, price FROM products WHERE id = %d;",
$product_id);
$result = mysql_query($sql);
//Only display the row if there is a product (though there should always be as we have already checked)
if(mysql_num_rows($result) > 0) {
list($name, $description, $price) = mysql_fetch_row($result);
$line_cost = $price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\"><strong>$name</strong></td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\"><strong>$quantity </strong>Borrar</td>";
echo "<td align=\"center\"><strong>$line_cost</strong></td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\"><strong>Total</strong></td>";
echo "<td align=\"right\"><strong>$total</strong></td>";
echo "</tr>";
echo "</table>";
}else{
//otherwise tell the user they have no items in their cart
echo "No tiene articulos en compra.";
}
//function to check if a product exists
function productExists($product_id) {
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = sprintf("SELECT * FROM products WHERE id = %d;",
$product_id);
return mysql_num_rows(mysql_query($sql)) > 0;
}
?>
</p>
<p><strong>Seguir Comprando</strong></p>
<?php
and now the display of the books / items / whatever you want.
<?php
define('MAX_REC_PER_PAGE', 1);
$sql = "SELECT id, name, description, price FROM products;";
$rs = mysql_query("SELECT COUNT(*) FROM products") or die("Imposible Realizar Operacion");
list($total) = mysql_fetch_row($rs);
$total_pages = ceil($total / MAX_REC_PER_PAGE);
$page = intval(#$_GET["page"]);
if (0 == $page){
$page = 1;
}
$start = MAX_REC_PER_PAGE * ($page - 1);
$max = MAX_REC_PER_PAGE;
$rs = mysql_query("SELECT id, name, description, price FROM products ORDER BY id
ASC LIMIT $start, $max") or die("Imposible Realizar Operacion");
?>
<table width="100%" height="404" border="0" cellpadding="12">
<?php
while (list($id, $name, $description, $price) = mysql_fetch_row($rs)) {
?>
<tr>
<td height="46" align="left" valign="middle"><p><strong> Producto :
<?= htmlspecialchars($name) ?>
</strong>
</p></td>
</tr>
<tr>
<td height="172" align="left" valign="middle"><p><strong>Descripcion :</strong></p>
<p>
<strong>
<?= htmlspecialchars($description) ?>
</strong></p></td>
</tr>
<tr>
<td height="67" align="left" valign="middle"><p><strong>Precio :
<?= htmlspecialchars($price) ?> </strong>
</p></td>
</tr>
<tr>
<td height="109" align="center" valign="middle"><strong><? echo "Comprar" ?> </strong></td>
</tr>
<?php
}
?>
</table>
<table border="0" cellpadding="5" align="center">
<tr>
<td><strong>Pagina : </strong></td>
<?php
for ($i = 1; $i <= $total_pages; $i++) {
$txt = $i;
if ($page != $i)
$txt = "$txt";
?>
<td align="center"><?= $txt ?></td>
<?php
}
?>
</table>
I have no idea where's the error on it...
Ty for the help :)
Obiusly you have to :
<?php session_start();?>
include your database
etc
You have in the style:
body {
background-image: url();
}
which is causing the browser to request the page again, which adds it to the cart again.
Instead of rendering the cart page, Once the code has modified the cart it should send a redirect to the cart page.