Can´t show message after form submit with header("location:") - php

I've search the forum for the same situation that I have but still couldn't find the solution. It's probably a piece of cake but I can't figure it out why my $_GET[] doesn't work.
I've created a product page and when I add something to the cart I want to display a message. I've made it work with the url in the form action but then my cart counter in the header stops working properly.
If it's possible I don't want to add any extra in the url like a "?success" because then it just keeps adding ?success to the url if I add more to the cart, that works in action but not with header() ?
Here is my code for the product page:
<?php include_once '../header.php';
$message = "";
$product = New Product;
$cart_data = [];
// if the variables are set - run the following statement
if(isset($_POST["addtocart"])) {
if(isset($_COOKIE["cart"])) {
// Removes backlashes and dont replace previous item, gives every item a new row.
$cookie_data = stripslashes($_COOKIE['cart']);
$cart_data = json_decode($cookie_data, true);
}
// Returns the productid and Size in the array
$item_list = array_column($cart_data, 'ProductsId');
$size_list = array_column($cart_data, 'Size');
// Returns the value if the statement is true
if(in_array($_POST["ProductsId"], $item_list) && in_array($_POST['selectedSize'], $size_list)) {
// A foreachloop that repeats the array value of the selected key variable.
foreach($cart_data as $keys => $values) {
if($cart_data[$keys]["ProductsId"] == $_POST["ProductsId"] && $cart_data[$keys]["Size"] == $_POST["selectedSize"]) {
$cart_data[$keys]["quantity"] = $cart_data[$keys]["quantity"] + $_POST["quantity"];
}
}
}
else {
$item_array = array(
'Img' => $Img = filter_var($_POST["Img"], FILTER_SANITIZE_STRING),
'ProductName' => $ProductName = filter_var($_POST["ProductName"], FILTER_SANITIZE_STRING),
'Size' => $Size = filter_var($_POST['selectedSize'], FILTER_SANITIZE_STRING),
'ProductsId' => $ProductsId = filter_var($_POST["ProductsId"], FILTER_SANITIZE_NUMBER_INT),
'Price' => $Price = filter_var($_POST["Price"], FILTER_SANITIZE_NUMBER_INT),
'quantity' => $quantity = filter_var($_POST["quantity"], FILTER_SANITIZE_NUMBER_INT),
);
$cart_data[] = $item_array;
}
$item_data = json_encode($cart_data);
setcookie('cart', $item_data, time() +(3600),'/');
header("location: product-detail.php?product=".$_GET['product']."?success");
}
if(isset($_GET['success'])) {
$message = "Varan lades till i varukorgen";
};
var_dump($message);
?>
<main id="product-content">
<section>
<form method="post" name="cartCount" action="">
<!-- product-detail.php?product=<?php echo $_GET['product']; ?> -->
<?php if(isset($_GET['product'])) {
$product->ProductsId = $_GET['product'];
$product->ProductId = $_GET['product'];
$product->ProductsId = $_GET['product'];
} else {
$product->ProductsId = $_POST['ProductsId'];
}
$result = $product->get_product();
$test = $product->get_productvariation();
while ($row = $result->fetch()) { ?>
<div class="product-card-detail">
<div class="product-image-wrapper">
<img class="product-image" src="../<?php echo $row['Img'];?>" >
<input type ="hidden" name="Img" value="<?php echo $row['Img'] ?>">
<?php $results = $product->get_images();
$Images = $results->fetch();
if(isset($Images['Image'])) { ?>
<img class="product-image" src="../<?php echo $Images['Image'];?>">
<?php } ?>
</div>
<div class="product-details-text">
<h2 class="title"><?php echo $row['ProductName']; ?></h2>
<input type ="hidden" name="ProductName" value="<?php echo $row['ProductName'] ?>">
<span class="price"><?php echo $row['Price'];?> SEK</span>
<input type ="hidden" name="Price" value="<?php echo $row['Price'] ?>">
<span class="select-title">Storlek</span>
<select class="size" name="selectedSize">
<?php while ($sizeRow = $test->fetch()) { ?>
<option>
<?php echo $sizeRow['Size']; ?>
</option>
<?php } ?>
</select>
<input type="hidden" name="quantity" value="1" />
<input type="submit" class="addtocart-btn" name="addtocart" value="Lägg i varukorgen"/>
<div><?php echo $message ?></div>
<input type ="hidden" name="ProductsId" value="<?php echo $row['ProductsId'] ?>">
<span class="title-description">Beskrivning</span>
<p class="description"><?php echo $row['Description']; ?></p>
</div>
</div>
<?php } ?>
</form>
</section>
</main>
<?php include_once "../footer.php";?>
I've made a test page that works exactly as expected so I can only think that is has to be something about the url?
Test code:
<?php
$message ="";
if(isset($_POST['submit'])) {
header("location: index.php?success");
}
if(isset($_GET['success'])) {
$message = "hello";
}
var_dump($message);
?>
<form method="post" action="">
<input text name="name" value="">
<input type="submit" name="submit" value="submit">
<?php echo $message ?>
</form>
Glad if anyone can see why it doesn't work!

You have made a mistake:
header("location: product-detail.php?product=".$_GET['product']."?success");
See the above line and notice that you are appending param success with ?.
Make it & as:
header("location: product-detail.php?product=".$_GET['product']."&success");

Related

How to post only variable with values and ignore blank inputs in PHP?

Forms input value variables are the same changing only labels for it from DB. When form selected other ones is hidden with "style.display = "none".
The problem that I face how to prevent sending empty values from none visible input fields?
Tried a trim function but didn't work for me. Maybe didn't use it correctly.
I'm trying to accomplish that input value would stay the same regardless of what user would select and only labels would change.
dump output
<?php
if (isset($_POST["save"])) {
if (empty($_POST['price'])) {
$error["price"] = "Price Required";
} else {
$price = $_POST["price"];
}
if (array_filter($error)) {
echo "Input error";
} else {
$price = ($_POST['price']);
$value1 = ($_POST['value1']) ?? null;
$value2 = $_POST['value2'] ?? null;
$value3 = $_POST['value3'] ?? null;
}
}
// insert size
$sql = "INSERT INTO valueSize(value1, value2, value3) values('$value1', '$value2, '$value3')";
$stmt = $pdo->prepare($sql);
$stmt->execute();
?>
<!DOCTYPE html>
<html lang="en">
<form action="">
<?php foreach ($categoriesTypeId as $key): ?>
<div class="dropItem invisible" id="<?php echo $key['id'] ?>">
<label for="value1"><?php echo $key['value1Type'] ?>:</label>
<input type="text" name="value1[]" value="<?php echo $value1 ?>">
<div class="error"><?php echo $error['value1'] ?></div>
<?php if (isset($key['value2Type'])) {?>
<div class="inputCheck">
<label for="value2"><?php echo $key['value2Type'] ?>
:</label>
<input type="text" name="value2" value="<?php echo $value2 ?>">
<div class="error"><?php echo $error['value2'] ?></div>
</div>
<?php
}
;
?>
<?php if (isset($key['value3Type'])) {?>
<div class="inputCheck">
<label for="value3"><?php echo $key['value3Type'] ?>
:</label>
<input type="text" name="value3" value="<?php echo $value3 ?>">
<div class="error"><?php echo $error['value3'] ?></div>
</div>
<?php
} else {
}
?>
<?php endforeach;?>
</form>
</html>

Add-to-cart coding is that correct with form?

<?php
session_start();
include("conn.php");
$action = $_POST['action'];
$user = $_SESSION['username'];
if(empty($user)){
echo"<script>alert('Please log in!');window.location='Log In.php';</script>";
exit;
}
if($action == 'add'){
$cart_arr = array(
'foodID'=>$_POST['foodID'],
'order_num'=>$_POST['order_num'],
'food_type'=>$_POST['food_type'],
);
$cart_session = $_SESSION['cart_'.$user];
if(empty($cart_session)){
$cart_session[$cart_arr['foodID']] = $cart_arr;
} else if(!empty($cart_session[$cart_arr['foodID']])){
$cart_session[$cart_arr['foodID']]['order_num']+=$cart_arr['order_num'];
} else {
echo $cart_session[$cart_arr['foodID']] = $cart_arr;
}
$_SESSION['cart_'.$user] = $cart_session;
} else if($action == 'clear'){
$_SESSION['cart_'.$user]=array();
echo"<script>alert('Shopping cart is empty, return home!');window.location='homepage.php';</script>";
exit;
} else if($action == 'change'){
$temp_cart = $_SESSION['cart_'.$user];
foreach($temp_cart as $k=>$v){
if($_POST['goods_'.$k]!= $v['order_num']){
$temp_cart[$k]['order_num'] = $_POST['goods_'.$k];
}
if($_POST['goods_'.$k] == 0){
unset($temp_cart[$k]);
}
}
$_SESSION['cart_'.$user] = $temp_cart;
}
if(empty($_SESSION['cart_'.$user])){
echo"<script>alert('Shopping cart is empty, please add some orders!');window.location = 'homepage.php';</script>";
exit;
}
$goods_id = array();
$cart = $_SESSION['cart_'.$user];
$v['food_type'] = $_POST['food_type'];
foreach($cart as $k=>$v){
$goods_id[$v['foodID']] = $v['foodID'];
}
$goods_id_str = implode(",",$goods_id);
mysql_query("set names utf8");
$sql = "select * from foodmenu where foodID IN (".$goods_id_str.")";
$query = mysql_query($sql);
$cart_goods = array();
while($arr = mysql_fetch_array($query)){
$cart_goods[$arr['foodID']] = $arr;
}
foreach($cart as $k=>$v){
$cart[$k]['food_name'] = $cart_goods[$k]['food_name'];
$cart[$k]['food_img'] = str_replace("../","",$cart_goods[$k]['food_img']);
$cart[$k]['food_price'] = $cart_goods[$k]['food_price'];
$cart[$k]['food_description'] = $_POST['food_description'];
}
?>
May I know is that this coding correct?
Because it shows blank page when it click on the button on previous php for add-to-cart purpose and it just shows normal header at the top.
I will attach form to access this php.
<div class="detailtop">
<?php
$result = mysql_query("SELECT * FROM foodmenu where foodID = '$foodID'");
while($row=mysql_fetch_array($result)){
?>
<dl>
<dt>
<img src="<?php echo $row["food_img"];?>" /> </dt>
<dd>
<form action="order.php" method="get" name="send" onSubmit="return Check()" enctype="multipart/form-data">
<h3><?php echo $row["food_name"];?></h3>
<div class="detailtips">
<?php echo $row["food_description"];?>
</div>
<p><span>Restaurant:</span><strong><?php echo $row["restaurant_name"];?></strong></p>
<p><span>Type :</span><strong><?php echo $row["food_type"];?></strong></p>
<p><span>Price :</span>RM <strong><?php echo $row["food_price"];?><input name="num" type="hidden" class="num" value="<?php echo $row["food_price"];?>" /></strong></p>
<div class="order" style=" padding-top:20px; padding-left:20px;">
<input name="id" type="hidden" value="<?php echo $row["foodID"];?>" />
<input name="" type="submit" value="" class="ordersubmit" style=" margin-left:30px; margin-top:20px;">
</div>
</form>
</dd>
</dl>
<?php }?>
</div>

edit_subject.php is not working, the error is saying about database query failed

This is kind of the error I'm getting:
Database query failed.
I've uploaded this webpage: http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1
Here's my file:
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php find_selected_page(); ?>
<?php
if (!$current_subject)
{
// subject ID was missing or invalid or
// subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit']))
{
// validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors))
{
// Perform Update
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "UPDATE subjects SET ";
$query .= "menu_name='{$menu_name}', ";
$query .= "position={$position}, ";
$query .= "visible={$visible} ";
$query .= "WHERE id={$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
// else
// {
// // This is probably a GET request
// }
?>
<?php include("../includes/layouts/header.php"); ?>
<div id="main">
<div id="navigation">
<?php
echo navigation($current_subject, $current_page);
?>
</div>
<div id="page">
<?php
// echo message();
// $message is just a variable, doesn't use the SESSION
if(!empty($message))
{
echo "<div class=\"message\">" . htmlentities($message) . "</div>";
}
?>
<?php echo form_errors($errors); ?>
<h2>Edit Subject: <?php echo htmlentities($current_subject["menu_name"]); ?></h2>
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="<?php echo htmlentities($current_subject["menu_name"]); ?>" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
for ($count=1; $count <= $subject_count; $count++)
{
echo "<option value=\"{$count}\"";
if ($current_subject["position"] == $count)
{
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" <?php if ($current_subject["visible"] == 0) { echo "checked"; } ?> /> No
<input type="radio" name="visible" value="1" <?php if ($current_subject["visible"] == 1) { echo "checked"; } ?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject" />
</form>
<br />
Cancel
Delete Subject
</div>
The problem is somewhere else and not with your UPDATE query actually. If you see the link you posted, you are passing subject parameter with url, whose value is 1 which is integer.
Now when you click submit it's changing the url to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=About%20Widget%20Corp .
Here as you see the subject parameter is not integer but string value name of subject. And that is causing the problem.
You are getting error as it's not retrieving the subject data from database correctly because of wrong id type. You just need to make sure the form is being posted to right url, which would be http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1.
You need to correct the action parameter on the <form> tag for that.
Look for the line below in your code:
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
And change it to
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["id"]); ?>" method="post">
If you see, now the form will be submitted to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1, which is the correct url.

Shopping cart no updating php using sessions

I have made a simple cart, my issue is when I want to update the quantity of a single product. I use the post method to do it. When I add in the quantity on the correct item and click on update, it does the update successfully but any other product their quantity is updated as well. Please help.
<?php
if(isset($_POST['Update']))
{
if(isset($_POST['prod_id']))
{
$myid = $_POST['prod_id'];
if (in_array($myid,$_SESSION['cart']))
{
$key = array_search($myid, $_SESSION['cart']);
$value_qty = "qtyval".$key;
$_SESSION[$key] = $_POST[$value_qty];
$message=$_SESSION[$key];
echo '<script>alert("'.$message.'")</script>';
}
}
}
?>
<?php
foreach ($_SESSION['cart'] as $key_value => $listitem)
{
$sql="SELECT * FROM products where id = '$listitem'";
$result_set = $database->query($sql);
while ($row=$database->fetch_array($result_set)){
?>
<div class="basket_block" id="basket_block">
<div class="item_block_remove" id="item_block_remove">Remove</div>
<div class="item_block" id="item_block">Name: <?php echo $row['Title_of_Message']; ?><br />
Description <?php echo $row['Description']; ?>
</div>
<div class="item_qty" id="item_qty"><form action="" method="POST" enctype="multipart/form-data" name="frmqty">
<input type="text" name="<?php echo (string)'qtyval'.$key_value; ?>" size="3" style="border-radius: 15px;text-align: center;" value="<?php
if(isset($_POST['Update']))
{
echo $_SESSION[$key];
}
else
{
echo $_SESSION[$key] = 1;
}
?>" />
<input type="hidden" name="prod_id" id="prod_id" value="<?php echo $row['id']; ?>" />
<input type="submit" value="Update" name="Update" style="border:none;cursor:pointer;padding-top:10px; background-color:transparent;" />
</form></div>

html form does not work inside fieldsets

I have a field set and inside it i have a form . it does not work . i mean to say . when i see the tags using firebug , the form tags will not be there at all..how do u i get over it.
this is how the code goes...its a php code..
<div id="dialog-form_surg_couns" title=" Surgical Counselling">
<?php
$surgCount = 0;
foreach($this->surgery as $surgery) {
$surgCount++;
$newId = str_replace(' ','',$surgery->getSurgeryname());
?>
<div class='fieldreq1Pct'>
<div class='fieldItemLabel'>
<label for=''><?php echo $surgery->getSurgeryname() ?></label>
</div>
<div class='fieldItemValue'>
<input type='checkbox' class='surg_couns_tests' id="<?php echo $newId ?>" name='surg_couns_tests' value="<?php echo $surgery->getSurgeryname() ?>" <?php echo (($showValue && strstr($visitRecord->getSurgcounstests(),$surgery->getSurgeryname())) ? 'checked' : "" ); ?> onClick="javascript:showBlock(this.id);">
</div>
</div>
<?php
if(($surgCount % 3) == 0)
{
?>
<div class='clear'></div>
<?php
}
}
?>
<div class='clear'></div>
<hr/>
<?php
foreach($this->surgery as $surgery) {
$newId = str_replace(' ','',$surgery->getSurgeryname());
$fieldCount = 0;
?>
<div id='<?php echo $newId ?>_block' style='display:none;' class='check_block'>
<form method='POST' action ='' id ='<?php echo $newId ?>_form'>
<table border='0' class='surg_table'>
<?php
foreach($this->surgeryTemplate as $surgerytemplate) {
if($surgery->getSurgeryid() == $surgerytemplate->getSurgeryid())
{
$fieldCount++;
$fieldName = 'field'.$fieldCount;
$fieldId = $surgerytemplate->getFieldid();
if($surgerytemplate->getRequired() == 'Y')
{
$required = 'required';
}
else
{
$required = '';
}
if($surgerytemplate->getType() == 'AN')
{
$validation = 'alpha';
}
else
{
$validation = '';
}
?>
<tr>
<td>
<?php echo $surgerytemplate->getFieldname(); ?>
</td>
<td>
<?php
if($surgerytemplate->getType() == 'B')
{
echo '<input type=\'radio\' name=\''.$fieldName.'\' value=\'Yes\'>Yes';
echo '<input type=\'radio\' name=\''.$fieldName.'\' value=\'No\'>No';
}
else
{
echo '<input type=\'text\' name=\''.$fieldName.'\' id=\''.$fieldName.'\' class=\''.$required.' '.$validation.'\' onblur="checkValid(this.id)"><div id=\''.$fieldName.'error\'></div>';
}
?>
</td>
</tr>
<?php
}
}
?>
</table>
<center><input type='button' name='submit' value='submit' onclick='javascript:submitSurgeryForm("<?php echo $newId ?>")'></center>
</form>
</div>
<?php
}
?>
</div>
You can't have a form tag inside another form. The following HTML is invalid:
<form>
<fieldset>
<form>
<input>
</form>
</fieldset>
</form>
The browser will silently ignore the second form, and instead will interpret your page as:
<form>
<fieldset>
<input>
</fieldset>
</form>

Categories