"Cannot modify header information" warning - php

I'm getting this warning while following a YouTube tutorial, and can't figure out why:
Warning: Cannot modify header information - headers already sent by (output started at /Applications/XAMPP/xamppfiles/htdocs/storeadmin/inventory_list.php:23
This is the code:
<?php
session_start();
if(!isset($_SESSION["manager"])){
header("location: admin_login.php");
exit();
}
$managerID = preg_replace('#[^0-9]#i','',$_SESSION["id"]);//filter everything but numbers
$manager= preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["manager"]);
$password= preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
include "../connect_to_mysql.php";//includes file to connect to db
$sql= mysql_query("SELECT * FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1");
$existCount=mysql_num_rows($sql); //count row
if ($existCount == 0) {
echo "your login does not exist";
exit();
}
?>
<?php
error_reporting(E_ALL);//error report testing
ini_set('display_errors','1');
?>
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysql_query("DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
//parse form data adds inventory item to database
if(isset($_POST['product_name'])){
$product_name = mysql_real_escape_string($_POST['product_name']);
$price = mysql_real_escape_string($_POST['price']);
$proddescription = mysql_real_escape_string($_POST['proddescription']);
$genre = mysql_real_escape_string($_POST['genre']);
$quantity = mysql_real_escape_string($_POST['quantity']);
//this checks if an item already exists under this name
$sql= mysql_query("SELECT id FROM products WHERE product_name='$product_name' LIMIT 1");
$productMatch = mysql_num_rows($sql);
if($productMatch > 0){
echo 'Sorry, this item already exists, click here';
exit();
}
//add items to database
$sql = mysql_query("INSERT INTO products (product_name, price, proddescription, genre, quantity)
VALUES('$product_name','$price','$proddescription','$genre','$quantity')") 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: inventory_list.php");
exit();
}
?>
<?php
//this displays whole list
$product_list="";
$sql = mysql_query("SELECT * FROM products");
$productCount =mysql_num_rows($sql);
if($productCount>0){
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$quantity = $row["quantity"];
$product_list.="$id - $product_name - $quantity - $price <a href= 'inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "There are no products in the store.";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<title>Inventory List</title>
<link href="../style2.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="container">
<div id="masthead">
</div>
<div id="navigation">
<p>Home
Fiction
Travel
Sport
Arts & Design
Shopping Cart
Manage Account</p>
</div>
<div id="content">
<div align ="right" style="margin-right:32px;">+ Add New Item</div>
<div align="left" style="margin-left:24px;">
</div>
<h4>Inventory List</h4>
<?php echo $product_list; ?>
<a name = "inventoryForm" id="inventoryForm"></a>
<h3>
↓ Add New Item Form ↓
</h3>
<form action="inventory_list.php" enctype="multipart/form-data" name="myForm" id="myForm" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%">Product Name</td>
<td width="80%"><label>
<input name="product_name" type="text" id="product_name" size="64" />
</label></td>
</tr>
<tr>
<td>Product Price</td>
<td><label>
£
<input name="price" type="text" id="price" size="12" />
</label></td>
</tr>
<tr>
<td>Description</td>
<td><label>
<input name="proddescription" type="text" id="proddescription" size="64" />
</label></td>
</tr>
<tr>
<td>Genre</td>
<td><label>
<select name="genre" id="genre" />
<option value=""></option>
<option value="Fiction">Fiction</option>
<option value="Travel">Travel</option>
<option value="Sport">Sport</option>
<option value="Arts & Design">Arts & Design</option>
</select>
</label></td>
</tr>
<tr>
<td>Product Image</td>
<td><label>
<input type="file" name="fileField" id="fileField" />
</label></td>
</tr>
<tr>
<td>Quantity</td>
<td><label>
<input name="quantity" type="text" id="quantity" size="4" />
</label></td>
</tr>
<tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Add Item" />
</label></td>
</tr>
</table>
</form>
<br />
<br />
</div>
<div id="footer">
<p>ADMIN AREA</p>
</div>
</div>
</body>
</html>

You have an empty line outside of php tags:
?>
<?php
This will cause php to send newlines.

This is happening in one of the header() calls in a later block. For example, in the third <?php ?> block it calls:
header("location: inventory_list.php");
You have empty lines between each <?php ?> block, so that counts as raw HTML and is sent to the user's browser as soon as it happens (the first line outside of a code block is line 23, which is why it's mentioned in the error). Before data can be sent the headers have to be sent, so at that point you can no longer change them. Since there's nothing between your PHP blocks but blank lines, you could just merge them all together to fix it

As the error says you cannot modify headers. So if you are using the header() function be sure that there is no space or content outside of <?php ?> tags. And don't send the same header twice inside the same script. There are several issues like this in your code:
...
echo "your login does not exist";
exit();
}
?>
//here you have space and \n
<?php
Merge all PHP blocks.

Related

Can't echo data from phpmyadmin

Am was already created form like this and working perfect but on last two forms not working, it displays warning-Undefined variable: reg_no and cost. Am trying to follow algorithm as previous forms but nothing happen. My goal is to update inserted data and here is my form
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Edit invoice</title>
<link rel="stylesheet" href="box_style.css" />
</head>
<body>
<?php
include ("db_con.php");
if(isset($_GET['edit_invoice'])){
$edit_i_id = $_GET['edit_invoice'];
$select_invoice = "select * from invoice where i_id='$edit_i_id'";
$run_query = mysqli_query($con, $select_invoice);
while ($row_invoice=mysqli_fetch_array($run_query)){
$i_id = $row_invoice['i_id'];
$reg_no = $row_invoice['reg_no'];
$cost = $row_invoice['cost'];
}
}
?>
<div class='form'>
<form action="" method="post" enctype="multipart/form-data" >
<table width="745" align="center" border="2">
<p style="text-align: center;"><strong><span style="text-decoration: underline;">EDIT INVOICE:</span></strong></p>
<tr>
<td align="right" bgcolor="#dbe5f1"><strong>Registration Number:</strong></td>
<td><input type="text" name="reg_no" id="reg_no" size="35" class="text" placeholder="Registration Number" value="<?php echo $reg_no; ?>" required=""/></td>
</tr>
<tr>
<td align="right" bgcolor="#dbe5f1"><strong>Cost(Tshs):</strong></td>
<td><input type="text" name="cost" id="cost" size="35" class="text" placeholder="Cost" value="<?php echo $cost; ?>" required=""/></td>
</tr>
<tr>
<td colspan="6" align="center" bgcolor="#dbe5f1" ><input type="submit" name="update" class="submit-button" value="SAVE CHANGES"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Remove while loop from your php code since update is for one record based on id
The code will be as :
if(isset($_GET['edit_invoice'])){
$edit_i_id = $_GET['edit_invoice'];
$select_invoice = "select * from invoice where i_id='$edit_i_id'";
$run_query = mysqli_query($con, $select_invoice);
$row_invoice = mysqli_fetch_array($run_query);
$i_id = $row_invoice['i_id'];
$reg_no = $row_invoice['reg_no'];
$cost = $row_invoice['cost'];
}
if isset($_GET['edit_invoice']) is false, your $reg_no is not present in later script (where you want to echo it).
Put $reg_no above your isset($_GET...) check and set it null or empty string.
$reg_no = null;
if (isset($_GET['edit_invoice'])) {
// your code...
}
Edit: Do the same for $cost and $i_id ;)
PLEASE consider Tom Uddings comment with SQL injections!

Image not saving with id name

Hey guys so I've made a system through which any picture upload from admin panel gets saved in a specific folder, according to the id!
But when I made some changes, My php website is not saving the picture with the id name and also its not storing more than 1 picture.
<?php
// This file is www.developphp.com curriculum material
// Written by Adam Khoury January 01, 2011
// http://www.youtube.com/view_play_list?p=442E340A42191003
// Connect to the MySQL database
include "connect.php";
?>
<?php
// Script Error Reporting
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($conn,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['product_name'])) {
$product_name = mysqli_real_escape_string($_POST['product_name']);
$price = mysqli_real_escape_string($_POST['price']);
$category = mysqli_real_escape_string($_POST['category']);
$subcategory = mysqli_real_escape_string($_POST['subcategory']);
$details = mysqli_real_escape_string($_POST['details']);
// See if that product name is an identical match to another product in the system
$sql = mysqli_query($conn,"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 = mysqli_query($conn,"INSERT INTO products (product_name, price, details, category, subcategory, date_added)
VALUES('$product_name','$price','$details','$category','$subcategory',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: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($conn,"SELECT * FROM products ORDER BY date_added DESC");
$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"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - $$price - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Inventory List</title>
<link rel="stylesheet" href="../style/style.css" type="text/css" media="screen" />
</head>
<body>
<div align="center" id="mainWrapper">
<?php include_once("../template_header.php");?>
<div id="pageContent"><br />
<div align="right" style="margin-right:32px;">+ Add New Inventory Item</div>
<div align="left" style="margin-left:24px;">
<h2>Inventory list</h2>
<?php echo $product_list; ?>
</div>
<hr />
<a name="inventoryForm" id="inventoryForm"></a>
<h3>
↓ Add New Inventory Item Form ↓
</h3>
<form action="inventory_list.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%" align="right">Product Name</td>
<td width="80%"><label>
<input name="product_name" type="text" id="product_name" size="64" />
</label></td>
</tr>
<tr>
<td align="right">Product Price</td>
<td><label>
$
<input name="price" type="text" id="price" size="12" />
</label></td>
</tr>
<tr>
<td align="right">Category</td>
<td><label>
<select name="category" id="category">
<option value="Clothing">Clothing</option>
</select>
</label></td>
</tr>
<tr>
<td align="right">Subcategory</td>
<td><select name="subcategory" id="subcategory">
<option value=""></option>
<option value="Hats">Hats</option>
<option value="Pants">Pants</option>
<option value="Shirts">Shirts</option>
</select></td>
</tr>
<tr>
<td align="right">Product Details</td>
<td><label>
<textarea name="details" id="details" cols="64" rows="5"></textarea>
</label></td>
</tr>
<tr>
<td align="right">Product Image</td>
<td><label>
<input type="file" name="fileField" id="fileField" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Add This Item Now" />
</label></td>
</tr>
</table>
</form>
<br />
<br />
</div>
<?php include_once("../template_footer.php");?>
</div>
</body>
</html>
You can't switch between mysqli and mysql using the same connection. (note mysql_insert_id).
Change mysql_insert_id to mysqli_insert_id($conn).
Also: change all mysqli_real_escape_string($_POST...) to mysqli_real_escape_string($conn, $_POST...) (... = POST name) and change mysql_num_rows to mysqli_num_rows($conn, $sql).
Check the php.net website for an overview of changes between mysql and mysqli.

Removing table items from database

How can I remove a product from my table once it has been purchased (the products being purchased are from the user's cart)? Please ask for any more code you require to try help me.
basically all the products are unique so there is only 1 of them ALL so it needs removed once someone buys it.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="assets/css/styles.css">
<?php
session_start();
include 'conn.php';?>
</head>
<body>
<p> <b> <a href="cart.php" >SHOPPING CART</a> - </b> TOTAL ITEMS:<?php total_items ();?> TOTAL PRICE: <?php total_price ();?> </p>
<?php echo $ip=getip();?>
<?php cart(); ?>
<form method="get" action="results.php" enctype="multipart/form-data">
<input type="text" name="user_search" placeholder="search for products"/>
<input type="submit" name="search" value="search"/>
</form>
<section>
<div class="row">
<form action="" method="post" enctype="multipart/form-data">
<table class="align-center">
<tr>
<th> Remove </th>
<th> Product(s) </th>
<th> Total Price </th>
</tr>
<?php
$total = 0;
global $conn;
$ip = getip ();
$select_price = " SELECT * FROM cart WHERE ip_add='$ip'";
$run_price = mysqli_query ($conn, $select_price);
while ($product_price = mysqli_fetch_array ($run_price)){
$product_id = $product_price ['product_id'];
$product_price ="SELECT * FROM products WHERE product_id='$product_id'";
$run_product_price = mysqli_query($conn, $product_price);
if (!$run_product_price) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
while($pp_price = mysqli_fetch_array ($run_product_price)){
$product_price = array ($pp_price ['product_price']);
$product_title = $pp_price ['product_title'];
$product_image = $pp_price ['product_image'];
$single_price = $pp_price['product_price'];
$values = array_sum($product_price);
$total +=$values;
?>
<tr>
<td> <input type="checkbox" name="remove[]" value="<?php echo $product_id;?>"/> </td>
<td> <?php echo $product_title; ?> <br>
<img src="product_image/<?php echo $product_image; ?>" height="50" width="50"> </td>
<td>£<?php echo $values ?></td>
</tr>
<?php }
}
?>
<tr>
<td> <b> Sub Total: </b> </td>
<td> £<?php echo $total ?></td>
</tr>
<tr>
<td><input type="submit" name="update_cart" value="Update Cart"> </td>
<td><input type="submit" name="continue" value="Continue Shopping "> </td>
<td>CHECKOUT </td>
</tr>
</table>
</form>
<?php
global $conn;
$ip = getip();
if(isset($_POST['update_cart'])){
foreach($_POST['remove'] as $remove_id){
$del_product = "delete from cart where product_id='$remove_id' AND ip_add='$ip'";
$run_del = mysqli_query($conn, $del_product);
if($run_del){
echo "<script> window.open ('cart.php', '_self') </script>";
}
}
}
if(isset($_POST['continue'])){
echo "<script> window.open ('index.php', '_self') </script>";
}
?>
</section>
</div>
</body>
</html>
The above is my cart.php page (where the users see their items and can go to the checkout which is just a buy now button for paypal payments. Once it has been purchased is when it should be removed from my db.
Run
"DELETE FROM products WHERE product_id='$product_id'"
You should be aware though that this method of doing SQL queries is vulnerable to SQL injection. I would recommend you switch to using parameterized queries.

PHP - clear cart from database after make the purchase

I am new in php, and the cart file is called wholesalecart.php
Every time, after I complete the order, and continue shopping, then add a new product into the cart, the previous product is still in the cart.
So I think I may need to clear the cart in the database after making the purchase, so that next time when I continue shopping, it will not keep the old items from the database.
The wholesalecart.php file code is below:
require_once("../login/protect.php");
//required for db connection
require_once '../includes/conn.php';
function updateDbCart(){
$userId = $_SESSION['id'];
//create our json cart if it exists ready to put in db
if (!empty($_SESSION['wholesalecart'])){
$jsonCart = json_encode($_SESSION['wholesalecart']);
} else {
$jsonCart = '';
}
//see if user already has a record in db for us else add it
$query = "SELECT count(*) as found FROM user_carts WHERE user_id='$userId'";
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
if($data['found']) {
$query = "UPDATE user_carts SET cart='$jsonCart' WHERE user_id='$userId'";
$result = mysql_query($query);
} else {
$query = "INSERT INTO user_carts (user_id, cart) VALUES ('$userId', '$jsonCart')";
$result = mysql_query($query);
}
}
if(!empty($_POST['sendwholesale']))
{
$i=0;
foreach ($_POST as $p => $q)
{
$i++;
if(ctype_digit($_POST['qty'.$i]))
{
$_SESSION['wholesalecart'][$_POST['prodid'.$i]] = $_POST['qty'.$i];
}
}
updateDbCart();
}
elseif (isset($_POST['update']))
{
$prod = $_POST['prodid'];
$qty = (ctype_digit($_POST['qty']) ? $_POST['qty'] : 1);
$_SESSION['wholesalecart'][$prod] = $qty;
updateDbCart();
}
elseif (isset($_POST['remove']))
{
$prod = $_POST['prodid'];
unset($_SESSION['wholesalecart'][$prod]);
updateDbCart();
}
elseif (isset($_POST['empty']))
{
unset($_SESSION['wholesalecart']);
updateDbCart();
}
$_SESSION['wholesaletotalItems'] = 0;
if (!empty($_SESSION['wholesalecart']))
{
foreach ($_SESSION['wholesalecart'] as $p => $q)
{
$_SESSION['wholesaletotalItems'] += $q;
}
}
$_SESSION['wholesaletotal'] = 0;
$cartTotal = 0;
//get the cart from db
$userId = $_SESSION['id'];
$query = "SELECT cart as cartDataFromDb FROM user_carts WHERE user_id='$userId'";
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);
$_SESSION['wholesalecart'] = json_decode($data['cartDataFromDb'], true);
if (!empty($_SESSION['wholesalecart']))
{
$displayContent = '
<table id="shopCart">
<tr class="tableHead">
<td>Product Code</td>
<td>Product Name</td>
<td class="center small">Price</td>
<td class="center qtysmall">Qty</td>
<td class="center small">Subtotal</td>
<td class="center small"></td>
</tr>
';
$i=0;
foreach ($_SESSION['wholesalecart'] as $p => $q)
{
$query = "SELECT * FROM products WHERE prodid='$p'";
$result = mysql_query($query);
while ($data = mysql_fetch_array($result))
{
$i++;
$price = sprintf('%.2f',$data['wholesaleprice']);
$subTotal = ($price * $q);
$displayContent .= '
<tr class="cartRow">
<td>'.$data['prodid'].'</a></td>
<td>'.$data['prodname'].'</td>
<td class="center">$'.$price.'</td>
<td class="center">
<form action="wholesalecart.php" method="post">
<input type="hidden" name="prodid" value="'.$data['prodid'].'" />
<input type="text" class="qty" name="qty" size="3" maxlength="3" value="'.$q.'" />
<input type="submit" class="update" name="update" value="Update" />
</form>
</td>
<td class="center">$'.$subTotal.'</td>
<td class="center">
<form action="wholesalecart.php" method="post">
<input type="hidden" name="prodid" value="'.$data['prodid'].'" />
<input type="submit" class="remove" name="remove" value="Remove" />
</form>
</td>
</tr>';
$checkout .= '
<input type="hidden" value="'.$data['prodname'].' - '.$p.'" name="item_name_'.$i.'"/>
<input type="hidden" value="'.$q.'" name="quantity_'.$i.'"/>
<input type="hidden" value="'.$price.'" name="amount_'.$i.'"/>
<input type="hidden" value="'.$i.'" name="count"/>
';
$_SESSION['wholesaletotal'] += $subTotal;
$cartTotal += $subTotal;
} //end while
} //end foreach
$i++;
//add button to email the cart if logged in
if(isset($_SESSION['username']))
{
$emailIt = '
<tr class="cartRow">
<form action="wholesalemailcart.php" method="post">
<td colspan="6">Additional comments:<br /><textarea style="width:450px;height:80px;" name="cartMessage">'.$_SESSION['cartMessage'].'</textarea></td>
</tr>
<tr class="actionsRow">
<td colspan="4"></td>
<td colspan="2" class="left">
<input type="submit" class="checkout" name="mail" value="Continue With Order" />
</form>
</td>
</tr>
';
}
$displayContent .= '
<tr class="freightRow">
<td colspan="2" class="center">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
'.$checkout.'
<input type="hidden" value="Shipping" name="item_name_'.$i.'"/>
<input type="hidden" value="1" name="quantity_'.$i.'"/>
<input type="hidden" value="'.$i.'" name="count"/>
</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="totalsRow">
<td></td>
<td></td>
<td class="subtotal">Subtotal</td>
<td class="subtotal">'.$_SESSION['wholesaletotalItems'].'</td>
<td class="subtotal">'.sprintf('%.2f',$_SESSION['wholesaletotal']).'</td>
<td></td>
</tr>
<tr class="actionsRow">
<td></td>
<td></td>
<td colspan="2" class="center">
<input type="hidden" value="_cart" name="cmd"/>
<input type="hidden" value="1" name="upload"/>
<input type="hidden" value="email#email.co.nz" name="business"/>
<input type="hidden" value="NZD" name="currency_code"/>
<!-- <input type="submit" class="checkout" name="Action" value="Checkout" /> -->
</form>
</td>
<td colspan="2" class="left">
<!-- old $emailIt -->
</td>
'.$emailIt.'
</tr>
</table>
';
}
else
{
$displayContent = '<p class="center">Sorry you have no items in your Shopping cart</p>
<p class="center">Continue Shopping?</p>';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- InstanceBegin template="/Templates/template.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<link href="../css/hbcl-styles.css" rel="stylesheet" type="text/css" media="screen" />
<link href="../css/menu.css" rel="stylesheet" type="text/css" media="screen" />
<link href="../css/shop.css" rel="stylesheet" type="text/css" media="screen" />
<link href="../css/map-styles.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="wrap">
<a name="top"></a>
<div id="header"></div>
<div id="main">
<div id="left-content">
<div id="left-menu">
<?php include('../includes/menu.php'); ?>
</div>
<?php include('../includes/left-sidebar.php'); ?>
</div>
<!-- InstanceBeginEditable name="content" -->
<div id="middle-content">
<h1>Wholesale Shopping Cart</h1>
<h3>Continue Shopping </h3>
<p>Select and add more products from the left hand dealer product menu to your shopping cart.
<br />
<br />
</p>
<h3>Shopping Cart Contents</h3>
<p>At any time you can select the <strong>Cart</strong> button at the bottom of the left hand menu to check the contents of your shopping cart.
<br />
<br />
</p>
<h3>Continue With Order</h3>
<p>Once your cart is complete, select <strong>Continue With Order</strong>.</p>
<p> </p>
<?php echo $displayContent ?>
</div>
<!-- InstanceEndEditable -->
<div id="right-content">
<?php include('../includes/right-sidebar.php'); ?>
</div>
<?php include('../includes/footer.php'); ?>
</div>
</div>
</body>
<!-- InstanceEnd -->
</html>
The Continue With Order button in the form tag, link to wholesalemailcart.php
<?php
session_start();
require_once("../login/protect.php");
//required for db connection
require_once '../includes/conn.php';
require_once '../classes/class.phpmailer.php';
if(isset($_POST['mail'])){
$_SESSION['cartMessage'] = $_POST['cartMessage'];
}
if (!empty($_SESSION['wholesalecart']))
{
$i=0;
$cartTotal=0;
foreach ($_SESSION['wholesalecart'] as $p => $q)
{
$query = "SELECT * FROM products WHERE prodid='$p'";
$result = mysql_query($query);
while ($data = mysql_fetch_array($result))
{
$i++;
$price = $data['wholesaleprice'];
$subTotal = ($price * $q);
$mailContent .= '
<tr class="cartRow">
<td>'.$data['prodname'].'</td>
<td>'.$data['prodid'].'</td>
<td class="center">$'.$price.'</td>
<td class="center">'.$q.'</td>
<td class="center">$'.sprintf('%.2f',$subTotal).'</td>
</tr>
';
$cartTotal += $subTotal;
} //end while
} //end foreach
$body = '<br />
<table id="shopCart">
<tr class="tableHead">
<td>Product Name</td>
<td>Code</td>
<td class="center">Price Per Item</td>
<td class="center qtysmall">Qty</td>
<td class="center small">Subtotal</td>
</tr>
'.$mailContent.'
<tr>
<td></td>
<td></td>
<td class="center"><strong>Subtotal</strong></td>
<td class="center">'.$_SESSION['totalItems'].'</td>
<td class="center">$'.sprintf('%.2f',$cartTotal).'</td>
</tr>
<tr class="totalsRow">
<td></td>
<td></td>
<td class="subtotal">Subtotal</td>
<td class="subtotal">'.$_SESSION['wholesaletotalItems'].'</td>
<td class="subtotal">'.sprintf('%.2f',$_SESSION['wholesaletotal']).'</td>
<td></td>
</tr>
<tr>
<td colspan="5" class="cartRow">Additional message: <strong>'.$_SESSION['cartMessage'].'</strong></td>
</tr>
</table>
';
}
if(!isset($_POST['confirmSend']))
{
$id = $_SESSION['id'];
$username = $_SESSION['username'];
$query = "SELECT * FROM logins WHERE id='$id' AND username='$username'";
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
$name = $data['name'];
$email = $data['email'];
$address = $data['address'];
$address1 = $data['address1'];
$address2 = $data['address2'];
$address3 = $data['address3'];
$city = $data['city'];
}
$displayContent = '
<h1>Shopping Cart Completion</h1>
<p><strong>Your details.</strong></p><br/>
<form action="'.$_SERVER['SCRIPT_NAME'].'" method="post">
<table>
<tr>
<td class="mailform" width="150">Company Name:</td><td> <p>'.$name.'</p></td>
</tr>
<tr>
<td class="mailform">Email Address:</td><td><p>'.$email.'</p></td>
</tr>
<tr>
<td class="mailform">Address:</td><td><p>'.$address1.'</p></td>
</tr>
<tr>
<td class="mailform"></td><td><p>'.$address2.'</p></td>
</tr>
<tr>
<td class="mailform"></td><td><p>'.$address3.'</p></td>
</tr>
<tr>
<td class="mailform"></td><td><p>'.$city.'</p></td>
</tr>
<tr>
<td class="mailform"></td><td><p>'.$address.'</p></td>
</tr>
</table>
<p><strong>Your Order will be sent Hauraki Brewing containing the following selections.</strong></p>
'.$body.'
<br />
<p>Please select <strong>Send Order</strong> to complete your wholesale order.</p><br/>
<input type="submit" name="confirmSend" value="Send Order">
</form>
';
}
elseif(!empty($_SESSION['wholesalecart']) && (isset($_POST['confirmSend']) || isset($_POST['ReconfirmSend']) ))
{
$id = $_SESSION['id'];
$username = $_SESSION['username'];
$query = "SELECT * FROM logins WHERE id='$id' AND username='$username'";
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
$name = $data['name'];
$email = $data['email'];
$address = $data['address'];
$address1 = $data['address1'];
$address2 = $data['address2'];
$address3 = $data['address3'];
$city = $data['city'];
}
if(isset($_POST['ReconfirmSend']))
{
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$location = $_POST['location'];
$address = $data['address'];
}
if(strlen($name) > 2 && strlen($email) > 2)
{
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress("XXXX");
$mail->AddReplyTo($email, $name);
$mail->WordWrap = 50;
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional attachemnt and name
$mail->IsHTML(true);
$mail->Subject = $name.' - Hauraki Brewing Wholesale Order';
$mail->Body = '
<br>
Order From: '.$name.' <br><br/>
Email: '.$email.'<br>
Address: '.$address1.'<br>
'.$address2.'<br>
'.$address3.'<br>
'.$city.'<br>
'.$address.'
<br><br>
<br><br>
'.$body.'
<br>
';
//$mail->AltBody = "$message";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
//send second email
$mail2 = new PHPMailer();
$mail2->From = $email;
$mail2->FromName = $name;
$mail2->AddAddress($email);
$mail2->AddReplyTo($email, $name);
$mail2->WordWrap = 50;
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional attachemnt and name
$mail2->IsHTML(true);
$mail2->Subject = $name.' - Hauraki Brewing Order Confirmation';
$mail2->Body = '
<br>
Thank you for your order.<br/><br/>A copy of the order you placed is included below. Please phone or email us immediately if you see any discrepancies in what you ordered.<br/>
'.$body.'
<br>
';
//$mail->AltBody = "$message";
if(!$mail2->Send())
{
echo "second Message could not be sent. <p>";
echo "Mailer Error: " . $mail2->ErrorInfo;
exit;
}
/**
*
* For debugging send a third email to david
*
*/
/*
* End debug section
*/
//header("Location: order-form.php?success=y");
//exit();
$displayContent .= '
<h1>Wholesale Order Completed</h1>
<p>Your wholesale order has been sent successfully. You should receive a confirmation email that your order has been sent.<br/><br/>
Thank you for your order, we appreciate your business. <br/><br/>
Continue shopping and place another order or logout.
</p>
';
}
else
{
$displayContent = '
<p class="error">Invalid Fields</p>
<p><strong>Please enter your details to continue.</strong></p><br/>
<form action="'.$_SERVER['SCRIPT_NAME'].'" method="post">
<table>
<tr>
<td class="mailform" width="150">Company Name:</td><td><input type="text" name="name" value="" maxlength="100" size="40"/></td>
</tr>
<td class="mailform">Phone:</td><td><input type="text" name="phone" value="" maxlength="100" size="40"/></td>
</tr>
<td class="mailform">Email Address:</td><td><input type="text" name="email" value=""maxlength="100" size="40" /></td>
</tr>
<td class="mailform">Location (Town/City):</td><td><input type="text" name="location" value="" maxlength="100" size="40" /></td>
</tr>
</table>
<p><strong>Your email will list these products.</strong></p>
'.$body.'
<p>This will email your Order Enquiry to Hauraki Brewing, click <strong>Send Enquiry</strong> to continue.</p><br/>
<input type="submit" name="ReconfirmSend" value="Confirm and send">
</form>
';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<body>
<div id="wrap"><a name="top"></a>
<div id="header"></div>
<div id="main">
<div id="left-content">
<div id="left-menu">
<?php include('../includes/menu.php'); ?>
</div>
<?php include('../includes/left-sidebar.php'); ?>
</div>
<!-- InstanceBeginEditable name="content" -->
<div id="middle-content">
<?php echo $displayContent ?>
</div>
<!-- InstanceEndEditable -->
<div id="right-content">
<?php include('../includes/right-sidebar.php'); ?>
</div>
<?php include('../includes/footer.php'); ?>
</div>
</div>
</body>
<!-- InstanceEnd --></html>
Welcome to the fun and sometimes frustrating world of PHP programming!!
If I am scrolling through this correctly, your cart is kept in session variables which is not uncommon... I use them too for my carts. You mentioned database, but didn't see that referenced for the cart... unless I missed it. SESSION variables "keep" for a variable amount of time depending on a lot of different settings (PHPINFO, timeouts, etc) or unless you physically clear them out yourself using unset.
If what you are describing is right, it sounds like you hit the nail on the head and need to clear the cart out between orders.
I did notice some code that looks like it might have been written for that purpose, but I might be wrong...
elseif (isset($_POST['empty']))
{
unset($_SESSION['wholesalecart']);
updateDbCart();
}
But looking through the code you provided, I can't see this being called anywhere. Are you just missing the call to clear out the cart?
I solved this question.
Just deleted
function updateDbCart(){
$userId = $_SESSION['id'];
//create our json cart if it exists ready to put in db
if (!empty($_SESSION['wholesalecart'])){
$jsonCart = json_encode($_SESSION['wholesalecart']);
} else {
$jsonCart = '';
}
Create a logout link and inside the logout page put these:
unset($_SESSION["wholesalecart"]);

All products being displayed instead of only one

i edited my code as below but the issue is that each time i click on the edit link, all of the products are being displayed instead of only the one beside which i clicked the edit link.
note: Sorry for posting another question relating to my other one. I could not add any more comments.
<?php
include_once("db_connect.php");
if(isset($_POST['update']))
{
$prod_id = $_POST['prod_id'];
$prod_name=$_POST['prod_name'];
$prod_brand=$_POST['prod_brand'];
$prod_price=$_POST['prod_price'];
// checking empty field
if(empty($prod_price))
{
//if name field is empty
if(empty($prod_price))
{
echo "<font color='red'>Price field is empty.</font><br/>";
}
}
else
{
//updating the table
//$result=mysql_query("UPDATE tblretprod SET prod_price='$prod_price' WHERE prod_id=$prod_id");
$result=mysql_query("UPDATE tblretprod SET prod_price='".$prod_price."' WHERE prod_id='".$prod_id."';");
//redirectig to the display page. In our case, it is index.php
header("Location: update.php");
}
}
?>
<?php
$prod_id = $_GET['prod_id'];
$result=mysql_query("SELECT a.prod_name, a.prod_brand, b.prod_price FROM tblproduct a, tblretprod b where a.prod_id = b.prod_id") or die(mysql_error());
?>
<html>
<title>Edit Product</title>
<body>
Home
<br/><br/>
<form name="edit" method="post" action="updprod.php">
<table border="0">
<?php
while($res=mysql_fetch_array($result))
{
$prod_name = $res['prod_name'];
$prod_brand = $res['prod_brand'];
$prod_price = $res['prod_price'];
?>
<tr>
<td>Product Name</td>
<td>
<input type="text" disabled="disabled" name="prod_name" value = "<?php echo $prod_name;?>"> </td>
</tr>
<tr>
<td>Brand</td>
<td>
<input type="text" disabled="disabled" name="prod_brand" value = "<?php echo $prod_brand;?>"> </td>
</tr>
<tr>
<td>Product Price</td>
<td>
<input type="text" name="prod_price" value = "<?php echo $prod_price;?>">
<input type="hidden" name="prod_id" value = "<?php echo $_GET['prod_id'];?>">
</td>
</tr>
<?php } ?>
<tr>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
Add in your select query in WHERE clause:
AND a.prod_id = ".$prod_id."
query:
"SELECT
a.prod_name,
a.prod_brand,
b.prod_price
FROM
tblproduct a, tblretprod b
where
a.prod_id = b.prod_id
AND a.prod_id = ".intval($prod_id).""
To make the query safer against SQL Injection i've added intval function like Kickstart well pointed out.

Categories