I'm wanting to make a URL that transfers all the placed product numbers (they are in multiple rows) from the cart into the URL to be passed to the next page. Not sure if this is possible!
I have tried making the URL with a variable:
$placeditems = $_POST['placeditems'];
$url = "myorder.php?id=".urlencode($placeditems);
As was requested in the comments, below is my coding for the entire file as of right now (with some edits from the suggested comments).
<?php
session_start();
$cart = $_COOKIE['crochetdamour'];
if(isset($_POST['clear'])) {
$expire = time() -60*60*24*7*365;
setcookie("crochetdamour", $cart, $expire);
header("Location:mycart.php");
}
if($cart && $_GET['id']) {
$cart .= ',' . $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("crochetdamour", $cart, $expire);
header("Location:mycart.php");
}
if(!$cart && $_GET['id']) {
$cart = $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("crochetdamour", $cart, $expire);
header("Location:mycart.php");
}
if($cart && $_GET['remove_id']) {
$removed_item = $_GET['remove_id'];
$arr = explode(",", $cart);
unset($arr[$removed_item-1]);
$new_cart = implode(",", $arr);
$new_cart = rtrim($new_cart, ",");
$expire = time() +60*60*24*7*365;
setcookie("crochetdamour", $new_cart, $expire);
header("Location:mycart.php");
}
$placeditems = $_GET['placeditems'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Crochet d'Amour</title>
<link rel="stylesheet" href="https://use.typekit.net/kfn2dzo.css">
<link href="SiteStyles.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<header class="clearfix">
<img src="images/ball.png" alt="Ball of yarn." id="ball"><img src="images/logo.png" alt="Crochet d'Amour" id="logo">
<?php include('includes/nav.inc');?>
</header>
<div class="clearfix">
<section style="width:100%;">
<h1>My Cart</h1>
<form method="get" action="<?php $_SERVER['PHP_SELF'];?>">
<table width="100%">
<tr>
<th class="hidden">Product ID</th>
<th>Placed Items</th>
<th>Item Name</th>
<th>Description</th>
<th>Price</th>
<th>Actions</th>
</tr>
<?php
$cart = $_COOKIE['crochetdamour'];
if ($cart) {
$i = 1;
include('includes/dbc.php');
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM orderplace WHERE orderplace_number = '$item'";
$result = mysqli_query($con, $sql);
if($result == false){
$mysql_error = mysqli_error($con);
echo "There was a query error: $mysql_error";
}else {
while($row=mysqli_fetch_assoc($result)) {
echo '<tr><td align="left" id="prodid" name="prodid" class="hidden">' .$row['product_id']. '</td>';
echo '<td align="left"><input type="text" name="placeditems" id="placeditems" value="' .$row['orderplace_number']. '"></td>';
echo '<td align="left" id="prodname" name="prodname">' .$row['product_name']. '</td>';
echo '<td align="left" class="desctd" id="proddesc" name="proddesc">' .$row['product_size']. ', ' .$row['product_gender']. ', ' .$row['product_theme']. ', ' .$row['product_specs']. '</td>';
echo '<td align="left" id="prodprice" name="prodprice">' .$row['product_price']. '</td>';
echo '<td align="left">Remove From Cart</td></tr>';
$sum += $row['product_price'];
}//end while
$i++;
}//end else
}//end foreach
}//end if
?>
<?php {echo '<tr><td align="right" colspan="5" style="font-size:110%;font-weight:400;" id="total" name="total">Total: ' .$sum. '</td></tr>';}
$url = "myorder.php?id=".urlencode($placeditems)."&total=".urlencode($sum);?>
</table>
<input type="submit" name="clear" value="Empty Cart" style="margin-left: 40px" class="emptycart"> <?php if(isset($url)) {echo '<input type="submit" name="order" value="Proceed with Order" style="margin-left: 40px" class="emptycart">';} ?>
</form>
</section>
</div>
<footer>
<p class="footerp">Copyright © 2018-2019 Crochet d'Amour. All Rights Reserved.</p>
</footer>
</body>
</html>
Just make your form post a GET action.
if , lets say you have a couple of fields:
<form method="get" action="<?php $_SERVER['PHP_SELF'];?>">
<input name="test" type="text"/>
<input name="test2" type="text"/>
<input type="submit" name="clear" value="Empty Cart" style="margin-left: 40px" class="emptycart"> <?php if(isset($url)) {echo '<input type="submit" name="order" value="Proceed with Order" style="margin-left: 40px" class="emptycart">';} ?>
</form>
It will produce a GET request with this params ?test=WATEVER_YOU_TYPED&test2=SECOND_FIELD&clear=Empty&20%Cart or whatever is enterpret whitespace, i do not remember that.
Related
I was wondering if anyone had the time to look at my code and give me a hand please. Basically I have a form I downloaded which allows me to click on "add row" and it adds as many input boxes as I need which works just fine.
The problem is that when I add them to the DB, it duplicates entries and in addition I don't get the array values, only the single values.
For example: If I add 2 entries, I get 4 entries in the DB and they all look like this:
client_ID | item_date | item_code | item_name | qty | cost | added_user
5 | 2020-07-06| Array | Array | Array | Array | Me
PHP Code
function escape($html) {
return htmlspecialchars($html, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}
if (isset($_POST['add_items'])) {
$entries = array( $item_code, $item_name, $qty, $cost);
$client_id = $_POST['client_id'];
$item_date = date("Y-m-d");
$added_user = $_SESSION['usr'];
foreach ($entries as $row) {
$data = array(
'client_id' => $client_id,
'item_date' => $item_date,
'item_code' => $item_code,
'item_name' => $item_name,
'qty' => $qty,
'cost' => $cost,
'added_user' => $added_user
);
$query = "INSERT INTO `invoiceitems` SET ";
$fields = array();
foreach ($data as $field => $value) {
$fields[] = "`$field` = '$value'";
}
$fields = implode(', ', $fields);
$query .= $fields;
mysqli_query($con, $query);
}
}
HTML FORM
<tr class="item-row">
<td><input name="item_code[]" autocomplete="off" /></td>
<td><input name="item_name[]" autocomplete="off" /></td>
<td><input name="cost[]" autocomplete="off" /></td>
<td><input name="qty[]" autocomplete="off" /></td>
<td><span class="price"></span></td>
</tr>
I have looked over many examples and I'm stuck. I would really appreciate if someone could help me out. Thanks in advance!
ENTIRE CODE:
<?php
include('../includes/main.php');
include_once('../includes/config.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="keywords" content="" />
<meta name="description" content="" />
<title></title>
<link rel="stylesheet" href="../css/style.css" type="text/css" media="screen" charset="utf-8" />
<script src="../js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="../js/global.js" type="text/javascript" charset="utf-8"></script>
<script src="../js/modal.js" type="text/javascript" charset="utf-8"></script>
<link rel='stylesheet' type='text/css' href='css/style.css' />
<link rel='stylesheet' type='text/css' href='css/print.css' media="print" />
<script type='text/javascript' src='js/jquery-1.3.2.min.js'></script>
<script type='text/javascript' src='js/example.js'></script>
</head>
<body>
<?php include_once('../includes/header.php'); ?>
<div id="wrapper">
<div id="minwidth">
<div id="holder">
<?php $current = 3; include_once('../includes/navigation.php');
if(!isset($_SESSION['usr']))
{
echo "<p align='center'><font color='#F78181'>You need to be logged in to view this page.</font></p>";
}
else{
$client_id = $_POST['client_id'];
$query = "select * from clients where id = '$client_id'";
$result = mysqli_query($con, $query);
//$client_id = $_POST['client_id'];
$item_code = $_POST['item_code'];
$item_name = $_POST['item_name'];
$qty = $_POST['qty'];
$cost = $_POST['cost'];
/// /// ADD INVOICE ITEMS
function escape($html) {
return htmlspecialchars($html, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
}
if (isset($_POST['add_items'])) {
/////////////////////////////////////////////////////////////////////////
$entries = array( $item_code, $item_name, $qty, $cost);
$client_id = $_POST['client_id'];
$item_date = date("Y-m-d");
$added_user = $_SESSION['usr'];
foreach ($entries as $row) {
$data = array(
'client_id' => $client_id,
'item_date' => $item_date,
'item_code' => $item_code,
'item_name' => $item_name,
'qty' => $qty,
'cost' => $cost,
'added_user' => $added_user
);
$query = "INSERT INTO `invoiceitems` SET ";
$fields = array();
foreach ($data as $field => $value) {
$fields[] = "`$field` = '$value'";
}
$fields = implode(', ', $fields);
$query .= $fields;
mysqli_query($con, $query);
}
}
/// end ADD INVOICE ITEMS
?>
<div id="desc">
<div class="body">
<div id="html" class="help">
<div id="page-wrap">
<textarea id="header">INVOICE</textarea>
<div id="identity">
<textarea id="address">
<?php
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result) )
{
echo "$row[first_name] $row[last_name]";
echo "\n$row[address] $row[address2]";
echo "\n$row[riding] $row[postal_code]";
echo "\n$row[city] $row[province]";
echo "\n$row[whatsapp]";
echo "\n$row[phone1]";
echo "\n$row[phone2]";
echo "\n$row[phone3]";
}
}
?>
</textarea>
<div id="logo">
<div id="logoctr">
Change Logo
Save
|
Delete Logo
Cancel
</div>
<div id="logohelp">
<input id="imageloc" type="text" size="50" value="" /><br />
(max width: 540px, max height: 100px)
</div>
<img id="image" src="images/logo.png" alt="logo" />
</div>
</div>
<div style="clear:both"></div>
<div id="customer">
<textarea id="customer-title">J.D. Auto Center</textarea>
<form name="add_items" enctype="multipart/form-data" accept-charset="UTF-8" method="POST" action="<?php $_SERVER['PHP_SELF']; ?>" />
<?php
echo "<input type='hidden' name='client_id' value='$_POST[client_id]' />"; ?>
<table id="meta">
<tr>
<td class="meta-head">Invoice #</td>
<td><textarea>000123</textarea></td>
</tr>
<tr>
<td class="meta-head">Date</td>
<td><textarea id="date"></textarea></td>
</tr>
<tr>
<td class="meta-head">Amount Due</td>
<td><div class="due"></div></td>
</tr>
</table>
</div>
<table id="items">
<tr>
<th>Item</th>
<th>Descrição</th>
<th>Preço de Unidade</th>
<th>Quantidade</th>
<th>Total</th>
</tr>
<tr class="item-row">
<td><input name="item_code[]" autocomplete="off" /></td>
<td><input name="item_name[]" autocomplete="off" /></td>
<td><input name="cost[]" autocomplete="off" /></td>
<td><input name="qty[]" autocomplete="off" /></td>
<td><span class="price"></span></td>
</tr>
<tr id="hiderow">
<td colspan="5"><a id="addrow" href="javascript:;" title="Add a row">Add a row</a></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Subtotal</td>
<td class="total-value"><div id="subtotal"></div></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Total</td>
<td class="total-value"><div id="total"></div></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Amount Paid</td>
<td class="total-value"><textarea id="paid"></textarea></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line balance">Balance Due</td>
<td class="total-value balance"><div class="due"></div></td>
</tr>
</table>
<input type="submit" class="button" name="add_items" value="SALVAR" /></p>
</form>
<div id="terms">
<h5>Terms</h5>
<textarea>Agradecemos a preferencia.</textarea>
<?php
var_dump($_POST);
var_dump($entries);
?>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div id="body_footer">
<div id="bottom_left"><div id="bottom_right"></div></div>
</div>
</div>
</div>
</div>
</div>
<?php include_once('../includes/footer.php'); ?>
</body>
</html>
<?php
}
?>
Looping through $entries = array( $item_code, $item_name, $qty, $cost); is not correct. You will have to loop through post data array of each item in invoice.
$query = "INSERT INTO `invoiceitems` (`client_id`, `item_date`, `item_code`, `item_name`, `qty`, `cost`, `added_user`) VALUES ";
$insert_rows = array();
//loop through item_code post data, inside this loop we will get other row data
foreach ($_POST['item_code'] as $k => $item_code_data) {
$insert_fields = array($client_id, $item_date, $item_code_data, $_POST['item_name'][$k], $_POST['qty'][$k], $_POST['cost'][$k], $added_user);
$insert_rows[] = implode("', '", $insert_fields);
}
if(count($insert_rows) > 0){
$insert_rows_data = " ('" . implode("'), ('", $insert_rows) . "') ";
mysqli_query($con, $query . $insert_rows_data);
}
I would need to see more of the code on the html side but my first thought is that the name is of each entry is being duplicated with no iterration. For example. If it adds a new tag with name="name" and the next one you add it also gives it name="name" where it should be adding a iteration like name= "name1" . After that the post page needs to be able to get all post data with variable names of an unknown quantity. . I have had good luck with while(isset($_POST) and then a for loop to iterate over the name variable. But i would need to see a more complete code set
I am having an issue to pass a textarea to another page when contains more than one line.
I have 3 pages:
1.-_testInsertText.php = INSERT a new text in Database
2.-_testShowText.php = SELECT the texts from Database and redirect to Modify Page
3.-_testTextModify.php = UPDATE the text passed by _testShowText.php
My structure from my table from Database:
CREATE TABLE `tblTest`
(
`clmSerie` int (11) NOT NULL
,`clmTextArea` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
If I insert a text with two lines through _testInsertText.php I am able to display correctly through _testShowText.php
My problem is in redirecting (through href) those records with more than one line to _testTextModify.php page (For 1 line is working fine). It is not redirecting.
Could you please help me?
My code can be found below:
1.-_testInsertText.php
<?php
$txtEvolucion = '';
if(isset($_POST['Insert']) && isset($_POST["txtEvolucion"]))
{
$txtEvolucion = $_POST["txtEvolucion"];
require_once('mysqli_connect.php');
echo "<br>". "txtEvolucion={" . $txtEvolucion ."}";
$query = "INSERT INTO tblTest (clmTextArea) VALUES (?)";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "s", $txtEvolucion);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo $affected_rows;
if($affected_rows == 1)
{
$txtEvolucion = '';
echo "Inserted";
mysqli_stmt_close($stmt);
}
else
{
ini_set('display_errors', 'On');
mysqli_stmt_close($stmt);
}
}
?>
<html>
<head>
<title>Insert TextArea</title>
</head>
<body>
<h1>Insert TextArea</h1>
<div id="divAgenda">
<form id="contact" action="" method="post">
<fieldset>
<textarea id="txtEvolucion" name="txtEvolucion" tabindex="4" cols="90" rows="7"
value="<?= $txtEvolucion ?> "
><?= $txtEvolucion ?></textarea><br><br>
<button name="Insert" type="submit" id="contact-submit" data-submit="...Sending">Insert</button><br>
</fieldset>
</form>
</body>
</html>
2.-_testShowText.php
<?php
$output = '';
require_once('mysqli_connect.php');
$query = mysqli_query($dbc,"SELECT clmSerie
,clmTextArea
FROM tblTest
"
) or die('Error to select!: {' . mysqli_error($dbc) . '}');
$count = mysqli_num_rows($query);
$output .= '<table border="1" align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>MODIFY </b></td>
<td align="left"><b>Id </b></td>
<td align="left"><b>Text Area </b></td>
</tr>';
while($row = mysqli_fetch_array($query))
{
$serie = $row['clmSerie'];
$descripcion = utf8_encode($row['clmTextArea']);
$descripcion = nl2br($descripcion);
$output .= '<tr><td align="left"><a href="_testTextModify.php?descripcion=' . $descripcion .
'&serie=' . $serie .
'">Modify
</a></td>
<td align="left">' .$serie . '</td>
<td align="left">' .$descripcion . '</td>
';
$output .= '</tr>';
}
?>
<html>
<head>
<title>Show TextArea</title>
</head>
<body>
<h1>Show TextArea</h1>
<?php echo $output;?>
</body>
</html>
3.-_testTextModify.php
<?php
$txtEvolucion = '';
$txtEvolucionOld = $_GET['descripcion'];
$idSerie = $_GET['serie'];
echo "<br>". "txtEvolucionOld={" . $txtEvolucionOld ."}";
if(isset($_POST['Modify']) && isset($_POST["txtEvolucion"]))
{
$txtEvolucion = $_POST["txtEvolucion"];
require_once('mysqli_connect.php');
echo "<br>". "txtEvolucion={" . $txtEvolucion ."}";
$query = "UPDATE tblTest
SET clmTextArea = ?
WHERE clmTextArea = ?
AND clmSerie = ?
";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "sss", $txtEvolucion, $txtEvolucionOld, $idSerie);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo $affected_rows;
if($affected_rows == 1)
{
$txtEvolucion = '';
echo "Modified";
mysqli_stmt_close($stmt);
}
else
{
ini_set('display_errors', 'On');
mysqli_stmt_close($stmt);
}
}
?>
<html>
<head>
<title>Modify TextArea</title>
</head>
<body>
<h1>Modify TextArea</h1>
<div id="divAgenda">
<form id="contact" action="" method="post">
<fieldset>
<textarea id="txtEvolucion" name="txtEvolucion" tabindex="4" cols="90" rows="7"
value="<?= $txtEvolucion ?> "
><?= $txtEvolucionOld ?></textarea><br><br>
<button name="Modify" type="submit" id="contact-submit" data-submit="...Sending">Modify</button><br>
</fieldset>
</form>
</body>
</html>
Thanks to comment by Sloan Thrasher, I modified _testTextModify.php and _testShowText.php
And now I am passing content to a hidden TextArea instead of a href to the modify page and it is working fine now when it comes with more than one line.
Thank you everyone :)
The new code below:
_testTextModify.php
<?php
if(isset($_POST['fromTestShowText']))
{
$txtEvolucionOld = $_POST['descripcion'];
$idSerie = $_POST['serie'];
}
if(isset($_POST['Modify']) && isset($_POST["txtEvolucionOld"]))
{
$txtEvolucionOld = $_POST["txtEvolucionOld"];
require_once('mysqli_connect.php');
$query = "UPDATE tblTest
SET clmTextArea = ?
WHERE clmSerie = ?
";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "ss", $_POST['txtEvolucionOld'], $_POST['idSerie']);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo "<br>". "affected_rows={" . $affected_rows ."}";
if($affected_rows == 1)
{
$txtEvolucionOld = $recibeSerieEvolucion = '';
echo "Modified";
mysqli_stmt_close($stmt);
}
else
{
ini_set('display_errors', 'On');
mysqli_stmt_close($stmt);
}
}
?>
<html>
<head>
<title>Modify TextArea</title>
</head>
<body>
<br>Show
<br>Insert
<h1>Modify TextArea</h1>
<div id="divAgenda">
<form id="contact" action="" method="post">
<fieldset>
<input type="hidden" readonly id="idSerie" name="idSerie" size="2" type="text" maxlength="100" tabindex="3"
value="<?= $idSerie ?>"
><br>
<textarea id="txtEvolucionOld" name="txtEvolucionOld" tabindex="4" cols="90" rows="7"
value="<?= $txtEvolucionOld ?> "
><?= $txtEvolucionOld ?></textarea><br><br>
<button name="Modify" type="submit" id="contact-submit" data-submit="...Sending">Modify</button><br>
</fieldset>
</form>
</body>
</html>
_testShowText.php
<?php
$output = '';
require_once('mysqli_connect.php');
$query = mysqli_query($dbc,"SELECT clmSerie
,clmTextArea
FROM tblTest
"
) or die('Error to select!: {' . mysqli_error($dbc) . '}');
$count = mysqli_num_rows($query);
$output .= '<table border="1" align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>MODIFY </b></td>
<td align="left"><b>Id </b></td>
<td align="left"><b>Text Area </b></td>
</tr>';
while($row = mysqli_fetch_array($query))
{
$serie = $row['clmSerie'];
$descripcion = utf8_encode($row['clmTextArea']);
//$descripcion = nl2br($descripcion);
$output .= '<tr><td align="left"><form action="_testTextModify.php" method="post">
<button name = "fromTestShowText" type="image"
value="Submit">Modify
</button>
</td>
<td align="left">' .$serie . '</td>
<td align="left"><input hidden readonly id="serie" name="serie" type="text"
value="'. $serie . '"
>
<textarea id="descripcion" name="descripcion" cols="50" rows="6"
value = "'.$descripcion.'"
readonly>'. $descripcion .'</textarea>
</td>
</form>';
$output .= '</tr>';
}
?>
<html>
<head>
<title>Show TextArea</title>
</head>
<body>
<br>Show
<br>Insert
<h1>Show TextArea</h1>
<?php echo $output;?>
</body>
</html>
My code is: (Edited after a suggestion from an answer)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SomuFinance - Personal Finance Manager</title>
<link rel="stylesheet" type="text/css" href="indexStyle.css">
<script src="scripts/jquery-3.1.0.min.js"></script>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div id="container">
<input type="submit" class="button" name="edit" value="Edit" />
<input type="button" class="button" name="delete" value="Delete" />
<input type="text" id="action" name="action">
<table id="listDB">
<tr>
<th>Select</th>
<th>ID</th>
<th>Category ID</th>
<th>Shop</th>
<th>Item</th>
<th>Quantity</th>
<th>Unit</th>
<th>Price Based On</th>
<th>MRP</th>
<th>Seller's Price</th>
<th>Last Updated On</th>
</tr>
<?php
$dbc = mysqli_connect('localhost','root','atlantis2016','itemDB')
or die("Error Connecting to Database");
if(isset($_POST['submit']))
{
echo "Action Set to ".$_POST['action'];
if($_POST['action']=='confirmDelete')
{
echo "Now Deleting!!";
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
$query1 = "SELECT DISTINCT category FROM grocery";
$result1 = mysqli_query($dbc, $query1)
or die("Error Querying Database");
while($row = mysqli_fetch_array($result1))
{
$category = $row['category'];
$query2 = "SELECT * FROM grocery WHERE category='$category' ORDER BY item ASC";
$result2 = mysqli_query($dbc, $query2)
or die("Error Querying Database");
echo '<tr>';
echo '<td class="catHead" colspan=11>'.$category.'</td>';
echo '</tr>';
$catCount=1;
while($inRow = mysqli_fetch_array($result2))
{
$id = $inRow['id'];
$shop = $inRow['shop'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
echo '<tr>';
echo '<td><input type="checkbox" value="' . $id . '" name="selected[]" /></td>';
echo '<td>'.$id.'</td>';
echo '<td>'.$catCount.'</td>';
echo '<td>'.$shop.'</td>';
echo '<td class="leftAligned">'.$item.'</td>';
echo '<td>'.$qnty.'</td>';
echo '<td>'.$unit.'</td>';
echo '<td>'.$price_based_on.'</td>';
echo '<td class="pri">₹'.$mrp.'</td>';
echo '<td class="pri">₹'.$sellers_price.'</td>';
echo '<td>'.$last_updated_on.'</td>';
echo '</tr>';
$catCount++;
}
}
mysqli_close($dbc);
?>
<input type="submit" value="Submit">
</table>
</div>
<div class="dialogBG">
<div id="deleteConfirmDialog" class="dialog">
<div class="closeDialog"></div>
<p>Sure you want to delete the selected Data?</p>
<input type="submit" id="confirmDelete" class="dialogButton" name="edit" value="Delete" />
<input type="button" class="dialogButton cancelButton" name="delete" value="Cancel" />
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(){
if($(this).val()=="Delete")
{
$(".dialogBG").fadeIn(200);
$("#deleteConfirmDialog").show(200);
$("#action").val('confirmDelete');
}
else if($(this).val()=="Edit")
{
}
});
$('#confirmDelete').click(function(){
$(".closeDialog").trigger("click");
});
$('#cancelDelete').click(function(){
});
$(".closeDialog").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$(".cancelButton").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$("form").submit(function(e){
alert("Form is being sumbitted!");
});
});
</script>
</body>
</html>
I want the elements for which the checkbox is selected, contained in the php array selected[], to be deleted from the database. Before deletion, I want a confirmation dialog box to open up, which will contain the "submit" button. This will cause the actual deletion. However, for some reason the above code doesn't work. I can't even be sure if the post is being submitted, as the line echo "Action Set to ".$_POST['action']; doesn't return any output. Please help.
I believe this entire section of code is not working (from manual testing).
if(isset($_POST['submit']))
{
echo "PHP Working here!";
echo "Action Set to ".$_POST['action'];
if($_POST['action']=='confirmDelete')
{
echo "Now Deleting!!";
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
Any ideas why?
you need to put these inputs inside a form and set an action. like below:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" role="form">
<input></input>
<input></input>
</form>
this will be your code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SomuFinance - Personal Finance Manager</title>
<link rel="stylesheet" type="text/css" href="indexStyle.css">
<script src="scripts/jquery-3.1.0.min.js"></script>
</head>
<body>
<div id="container">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" role="form">
<input type="submit" class="button" name="edit" value="Edit" />
<input type="button" class="button" name="delete" value="Delete" />
<input type="text" id="action" name="action">
<table id="listDB">
<tr>
<th>Select</th>
<th>ID</th>
<th>Category ID</th>
<th>Shop</th>
<th>Item</th>
<th>Quantity</th>
<th>Unit</th>
<th>Price Based On</th>
<th>MRP</th>
<th>Seller's Price</th>
<th>Last Updated On</th>
</tr>
<?php
$dbc = mysqli_connect('localhost','root','atlantis2016','itemDB')
or die("Error Connecting to Database");
if(isset($_POST['submit']))
{
echo "Action Set to ".$_POST['action'];
if($_POST['action']=='confirmDelete')
{
echo "Now Deleting!!";
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
$query1 = "SELECT DISTINCT category FROM grocery";
$result1 = mysqli_query($dbc, $query1)
or die("Error Querying Database");
while($row = mysqli_fetch_array($result1))
{
$category = $row['category'];
$query2 = "SELECT * FROM grocery WHERE category='$category' ORDER BY item ASC";
$result2 = mysqli_query($dbc, $query2)
or die("Error Querying Database");
echo '<tr>';
echo '<td class="catHead" colspan=11>'.$category.'</td>';
echo '</tr>';
$catCount=1;
while($inRow = mysqli_fetch_array($result2))
{
$id = $inRow['id'];
$shop = $inRow['shop'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
echo '<tr>';
echo '<td><input type="checkbox" value="' . $id . '" name="selected[]" /></td>';
echo '<td>'.$id.'</td>';
echo '<td>'.$catCount.'</td>';
echo '<td>'.$shop.'</td>';
echo '<td class="leftAligned">'.$item.'</td>';
echo '<td>'.$qnty.'</td>';
echo '<td>'.$unit.'</td>';
echo '<td>'.$price_based_on.'</td>';
echo '<td class="pri">₹'.$mrp.'</td>';
echo '<td class="pri">₹'.$sellers_price.'</td>';
echo '<td>'.$last_updated_on.'</td>';
echo '</tr>';
$catCount++;
}
}
mysqli_close($dbc);
?>
</table>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(){
if($(this).val()=="Delete")
{
$(".dialogBG").fadeIn(200);
$("#deleteConfirmDialog").show(200);
$("#action").val('confirmDelete');
}
else if($(this).val()=="Edit")
{
}
});
$('#confirmDelete').click(function(){
$(".closeDialog").trigger("click");
});
$('#cancelDelete').click(function(){
});
$(".closeDialog").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$(".cancelButton").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
});
</script>
<div class="dialogBG">
<div id="deleteConfirmDialog" class="dialog">
<div class="closeDialog"></div>
<p>Sure you want to delete the selected Data?</p>
<input type="submit" id="confirmDelete" class="dialogButton" name="edit" value="Delete" />
<input type="button" class="dialogButton cancelButton" name="delete" value="Cancel" />
</div>
</div>
</body>
</html>
The solution was simple. if(isset($_POST['confirmDelete'])) needs to be there instead of if(isset($_POST['submit'])) in the problem section in the question as there is no button called "submit" in the entire form.
I have an app in php where I have to filter some products by category using Ajax and I don't have any idea how.
My all php code:
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1 align="center">Products </h1>
<!-- Products List Start -->
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, price FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<form method="post" action="cart_update.php">
<table>
<tr>
<td> Name: {$obj->product_name}</td>
<td>Category: {$obj->product_desc}</td>
<td> Price: {$currency}{$obj->price} </td>
<td>
<span>Color: </span>
<select name="product_color">
<option value="Black">Black</option>
<option value="Silver">Silver</option>
</select>
</td>
<td>
<span>Quantity: </span>
<input type="text" size="2" maxlength="2" name="product_qty" value="1" />
</td>
<td>
<div align="center"><button type="submit" class="add_to_cart">Add</button></div></td>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
</div></div>
</form>
</table>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
<!-- Products List End -->
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
echo '<h3><center>Your Shopping Cart</center></h3>';
echo '<form method="post" action="cart_update.php">';
echo '<table width="30%" cellpadding="6" cellspacing="0"';
echo '<tbody>';
$total =0;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$product_color = $cart_itm["product_color"];
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /> Remove</td>';
echo '</tr>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
echo '<td colspan="4">';
echo '<button type="submit">Update</button>';
echo '</td>';
echo '</tbody>';
echo '</table>';
echo '</h1>';
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
?>
<div id="maindiv">
<select id="options">
<option value="v1">Category</option>
</select>
<table id="destinations" border="1">
<tr>
<th>Product</th>
<th>Category</th>
<th>Price</th>
<th>Color</th>
<th>Quantity</th>
</tr>
</table>
</div>
</body>
</html>
I really can not understand how to make this filter.Can someone gives me some ideas in order to resolve this task?
You haven't given us much to go on in terms of what this "filter" is. If I assume by "filter" you mean you wish to alter your SQL query according to some user-initiated AJAX call(s) to this script, then you'll need the following:
A POST or GET request sent via AJAX containing the database fields you wish to filter on. Note: Use some sort of alias or map instead of passing actual database column-names where the user can see it, that'd be a security flaw - also ensure you escape (clean-up) any user-input before it goes anywhere near your SQL queries :-)
A WHERE clause to insert into your SQL query, constructed dynamically from the above POST or GET data
That's pretty much it.
Very Rough example:
$sql = "SELECT product_code, product_name, product_desc, price FROM products";
// Where $_POST['filter'] comes from an AJAX POST request in the frontend
if (!empty($_POST['filter'])) {
$codeSql = ' ' . (!empty($_POST['code']) ? "product_code = '" . mysqli_escape_string($_POST['code']) . '" : '');
$nameSql = ' ' . (!empty($_POST['name']) ? "product_name = '" . mysqli_escape_string($_POST['name']) . '" : '');
$sql .= "WHERE " . $codeSql . $nameSql;
}
$sql .= " ORDER BY id ASC";
$results = $mysqli->query($sql);
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"]);