upload and display multiple images for one product? - 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.

Related

PHP giving specific item access to admins

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.

not display from database

I'm trying to display list from database but when run that code it said "You have no product listed in your data yet" but actually have list from my data ...
<?php
$con = new mysqli("localhost", "root", "3250", "shopone");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This block grabs the whole list of product for viewing
$product_list = "";
$sql = "SELECT * FROM product ORDER BY product_id DESC";
$result=mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
$product_id = $row["product_id"];
$product_name = $row["product_name"];
$product_category = $row["product_category"];
$product_retail_price = $row["product_retail_price"];
$product_price = $row["product_price"];
$product_detail = $row["product_detail"];
$product_image = $row["screenshot"];
$product_thumbnail = $row["product_thumbnail"];
$product_discount = $row["product_discount"];
$screenshot = $row["screenshot"];
$product_list .= '<table width="80%" border="1">
<tr>
<td width="172" valign="top"> echo <img src="' . GW_UPLOADPATH . $screenshot .'" width="111" height="149" alt="<?php echo $product_name; ?>" /><br />
View Full Size Image</td>
<td width="85" class="product-text">' . $product_id . '</td>
<td width="402" class="product-text">' . $product_name . '</td>
<td width="108" align="center" class="product-text">' . $product_price . '</td>
<td width="34" align="center" class="product-text"><a rel="leanModal" href="edit_product.php?pid=' . $product_id . '">Edit</a></td>
<td width="56" align="center" class="product-text"><a rel="leanModal" href="product.php?deleteid=' . $product_id . '">Delete</a></td>
<td width="56" align="center" class="product-text">View</td>
</tr>
</table> ';
}
$product_list = "You have no product listed in your data yet";
?>
and then the result i get is showing nothing it said "you have no product list in your data" , how can i solve that!
Change the last assignment to:
if (empty($product_list)) {
$product_list = "You have no product listed in your data yet";
}
You were replacing all the results retrieved from the database with that error message.
All the places where you do <?php echo ... ?> in the $product_list assignments should be concatenation -- you can only use that in inline HTML, not in strings.
You probably don't want to start a new <table> for each row from the database. Usually there's just one HTML table, and each database row corresponds to one HTML row within it.
Maybe the privilege problem. But first comment the last line and have a try.
You are overwriting $product_list in the last statement, that´s why you get the value you last gave to the variable.
Also, as a tip, in the while loop you can save the row for each record, as you already have it in the array.
Last, you can open the table before the while, and close it after.
<?php
$con = new mysqli("localhost", "root", "3250", "shopone");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This block grabs the whole list of product for viewing
$sql = "SELECT * FROM product ORDER BY product_id DESC";
$result = mysqli_query($con,$sql);
//you can add this check to add 'empty table' message if no result
if(mysql_num_rows()>0)
{
$product_list = '<table>';
while($row = mysqli_fetch_array($result))
{
$product_list.= '<tr>'.
'<td>'.$row["product_id"].'</td>'.
// ....
// do the same with all rows
// ....
'<td>'.$row["screenshot"].'</td>'.
'</tr>';
}
$product_list.= '</table>';
}
else
{
$product_list = "You have no product listed in your data yet";
}
//print
echo $product_list;
?>

PHP website search and display items

I am creating a dummy online store to illustrate some real world functionality which one of them is to search the website for items i.e.
I have written PHP code to deal with this scenario but it does not work properly. Wchat it does dough is it matches the results and the number of results but it does not display them which I of course wont it to do.
Been trying to look for answers on GOOGLE but didn't find corresponding solution or a tip to my problem.
Here am gonna list the code I am using:
PHP code (search.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';
if (isset($_POST['keyword']))
{
$search = $_POST['keyword'];
if (!empty($search))
{
$query = "SELECT product_name FROM products WHERE product_name='$search'";
$query_search = mysql_query($query);
echo mysql_num_rows($query_search);
if (mysql_num_rows($query_search) >=1)
{
echo 'Results found: <br>';
while ($query_row = mysql_fetch_row($query_search))
{
echo $query_row['product_name'];
}
while($rows = mysql_fetch_array($query_search))
{ ?>
<table id='display'>
<tr><td><?php echo "<img src=$rows[$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 "$rows[$product_name]" ?></td>
<td width='290px'><?php echo "$rows[$product_qua]" ?></td>
<td width='290px'><?php echo "£ $rows[$product_price]" ?></td>
<td width='290px'><?php echo "$rows[$product_des]" ?></td>
</tr>
<tr>
<td><p>Please Login To purchase this item </p><br />Login</td>
</tr>
</table>
<?php
}
} else {
echo 'NO results found.';
}
}
}
?>
HTML code (index.php):
<form action="search.php" method="post">
<input type="text" name="keyword" size="20" placeholder="Search for products...."/>
<input type="submit" value="Search >>" />
</form>
Print screen of current result:
As you have have noticed it also says 3 results have been found which is correct considering i have searched for ever which is a common name of my product but drows up only two tables moreover they are empty.
website url: http://studentnet.kingston.ac.uk/~k1024026/index.php
finally my product table consists of : product_id product_name product_qua product_price product_image product_des product_type attrebiutes/columns
anyone can spot where i might be going wrong with this....?
First, try removing this
while ($query_row = mysql_fetch_row($query_search))
{
echo $query_row['product_name'];
}
I also noticed a few bad typo in your code :
table id="display" an id should be unique. If you iterate over it and still want it to be an id, put display-n instead, n being the unique id of the product for example. (or use class="display" instead of id)
You should take a look at sql injection and how to defeat them.
I might rather do this:
$query = "SELECT product_name FROM products WHERE product_name LIKE %" . $search . "%";
Hope it will help. Then use a foreach loop to run through the result like:
foreach ($search as $key => $result){
echo $result . '<br />';
}
mysql_fetch_row( $query_search) returns a plain array not an associative array but you are trying to access its values using keys - $query_row [ 'product_name' ]. Rather use _fetch_array
There are lots of syntactical errors. There is a space between function name and list of parameters.
Don't use mysql_. They are deprecated (read: dead). Use PDO instead.

PHP MySQL Shopping Cart - Adding items to session

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']));

Using dynamic urls to populate jquery slideshow

I am trying to dynamically populate a jquery slideshow using dynamic urls. The way this theoretically should work is the list with the images will contain dynamic links instead of the standard static links. So instead of having example.com/pics/specificpicture.jpg it would be example.com/pics/id?id=[this is what I don't know what to put]... the primary issue besides not knowing what to put there is that not only do I not know what to do to make a dynamic url, I also don't know how to make a list work proper. To explain, the jquery slideshow carousel I am using will have 6 images displaying at once, moving to the left every five seconds with the last picture being taken off to put a new picture on, so how would I keep the images from going in order, and thus each list would repeat images that another image already displayed?
EDIT this is some code very similar to what I am trying to do
PHP
<?php
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "storescripts/connect_to_mysql.php";
$dynamicList = "";
$sql = mysql_query("SELECT * FROM products ORDER BY date_added DESC LIMIT 6");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
while ($row = mysql_fetch_array($sql)) {
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$dynamicList .= '<table width="100%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="17%" valign="top"><img style="border:#666 1px solid;" src="inventory_images/' . $id . '.jpg" alt="' . $product_name . '" width="77" height="102" border="1" /></td>
<td width="83%" valign="top">' . $product_name . '<br />
$' . $price . '<br />
View Product Details</td>
</tr>
</table>';
}
} else {
$dynamicList = "We have no products listed in our store yet";
}
mysql_close();
?>
HTML
<td width="35%" valign="top">
<h3>Title</h3>
<p><?php echo $dynamicList; ?><br />
</p>
<p><br />
</p>
</td>
This is from developphp.com, basically how this is echoing a dynamic list, what I am trying to to is similarly echo a list, but with the 6 dynamic urls... even if I could do random images (which would not be near as productive as desired) i'd be thankful to have that much up there for now :/

Categories