Updating a specific key within a multidimensional array (PHP) - php

I'm having some difficulty updating a quantity value in a multi-dimensional array I've created and really hoping you can help me correct where I've gone wrong;
.
The background
I've got two "items" which both have a simple form tag followed by a hidden input field with a unique value (1 for the first item, 2 for the second).
The button will just point back to this same page using the POST method.
The div on the right of the page will then load a "basket" which will use these post values and add them to an array.
When the "add" button is used again the value should update to +1 rather than create another sub_array.
.
What is currently happening
Currently when I click "add" the first time it adds the array as expected;
However when clicking "add" for the second time it adds a second array rather than +1'in the quantity.
On the third time clicking "add" it does actually now find the original value and update it as I expected, if I click again and again it will continue to update the quantity
It just seems to be that second time I click "add".
.
The Script
<?php session_start();
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
if (ISSET($_POST["prod"]))
{
if(in_array($_POST["prod"],$_SESSION["cart"])==TRUE)
{
$_SESSION["cart"][0] =
array($_POST["prod"],$_POST["name"],$_SESSION["cart"][0][2]+1);
}
else{
echo 'running else';
$_SESSION["cart"]=array($_POST["prod"],$_POST["name"],1);}}
if ($_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
}
Sample form
<form action="test.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
Also, what you might well notice from my script is that when you "add" the second item it will actually overwrite the first one by creating the array from scratch so if you can help me with either or both of these I really would appreciate the expertise!
Many thanks to all in advance!

I tried to debug your code and a possible solution could be the following:
<?php
session_start();
if(!isset($_SESSION["cart"]))
{
$_SESSION["cart"]=[];
}
if (isset($_POST["prod"]))
{
$prod_id=$_POST["prod"];
//let suppose $_POST['prod'] is your item id
$found=false;
for($i=0;$i<count($_SESSION['cart']);$i++)
{
if(isset($_SESSION['cart'][$prod_id]))
{
echo "found! so add +1";
$_SESSION['cart'][$prod_id][2]+=1;
$found=true;
break;
}
}
if($found==false)
{
echo 'not found! so create a new item';
$_SESSION["cart"][$prod_id]=array($_POST["prod"],$_POST["name"],1);
}
}
if (isset($_POST['e']) && $_POST['e']=='1')
{
$_SESSION['cart'] = '';
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
?>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="2" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
Another way to do it is using associative arrays.
The following code creates a cart array in $_SESSION using the item name as key(so you don't need to loop over the cart array to find the item) and
an array with properties as name=>value for each item.
session_start();
if(!isset($_SESSION["cart"]))
{
$_SESSION["cart"]=[];
}
//let's suppose you have unique names for items
if (isset($_POST["prod"]))
{
$name=$_POST["name"];
if(isset($_SESSION['cart'][$name]))
{
echo "found! so add +1";
$_SESSION['cart'][$name]['quantity']+=1;
}
else
{
echo 'not found! so create a new item';
$_SESSION["cart"][$name]=array("id"=>$_POST["prod"],"name"=>$_POST["name"],"quantity"=>1);
}
}
if (isset($_POST['e']) && $_POST['e']=='1')
{
$_SESSION['cart'] =[];
}
echo '<br /><br />';
print_r($_SESSION["cart"]);
?>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="1" name="prod" />
<input type="hidden" value="MAST-O-MIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>
<form action="cart2.php" method="post" enctype="application/x-www-form-urlencoded">
MAST-O-MIR<br/>
img<br/>
£2.00<br/>
<input type="hidden" value="2" name="prod" />
<input type="hidden" value="MAST-OMIR" name="name" />
<button class="plus-btn" type="Submit">Add</button>
</form>

It's hard to test your code without a sample form but I guess both of your problems may be solved by replacing:
$_SESSION["cart"][0] = array($_POST["prod"], $_POST["name"], $_SESSION["cart"][0][2]+1);
For:
$_SESSION["cart"][0][2]+= 1;
By the way, try to properly indent your code when you are going to post it. It is hard to read.

Related

Add value from a form into a function

I have the following form:
<form action="myform.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="my-add-calc" value="add to cart" class="button" />
<input id="my-item-calc" name="my-item-calc" value="29.00">
<input type="hidden" name="my-item-id" value="1"></td>
<td><input type="submit"></form>
I want to use the submitted value of my-item-calc in a function:
I have tried
public function add_calc($calcdel){
$validCaldel = false;
if (is_numeric($calcdel)){
$validCaldel= true;}
//add calculated delivery
if ($validCaldel !==false){
$this->calcdels = $calcdel;}
}
Where
$calcdel = $config['calc']['calcdel'];
in the config file:
$config['checkoutPath'] = 'myform.php';
$config['calc']['calcdel'] = 'my-item-calc';
When I try to return $this->caldels its says this is an array, Im not sure why as I am only adding one value.
I would want the $this->calcdels to echo out the submitted 29.00
Any help very welcome
In your myform.php you shoud first get the value you're looking for:
$my_item_calc = $_POST[ 'my-item-calc' ];
and then give it to the function:
add_calc( $my_item_calc );

PHP: why variable does not get reloaded after a Submit?

Here is a code that I've made:
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if(isset($_POST['name'])){
$sum+=1;
}
echo "sum = $sum";
?>
When I enter some text in the form and click Validate, the page display sum=1, but after this, when I enter nothing in the form and click Validate, the page STILL displays sum=1.
Why does the variable $sum is not reloaded between the two Validate ? Is there a way to escape it ?
Thanks
This will solve the issue
<?php
$sum=0;
if(isset($_POST['name']) && $_POST['name'] != ''){
$sum+=1;
}
echo "sum = $sum";
?>
This is because isset() checks for the existence of the $_POST variable. In your case, the $_POST variable exists and has an empty string value.
Your code will work if you change isset() to !empty() like so;
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if(!empty($_POST['name'])){
$sum+=1;
}
echo "sum = $sum";
?>
More about the empty() function here.
Another way would be to check the request that your client has made on your page. So that if it is a simple refresh (not with a form refresh), it is a GET request and so, the variable should not be incremented and if the form has been sent, then you can do whatever you want such as incrementing the data.
So if the client is sending the form with an input text filled, then you can increment the value. In all other cases, the value should remain a zero.
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['name']) && !empty($_POST['name']))
{
$sum++; /* strictly equivalent to: $sum += 1; */
}
?>
<samp>sum = <?php echo $sum; ?></samp>
Try this
<form method="post" action="test.php">
<input type="text" name="name" placeholder="name"/><br />
<input type="submit" name="submit" value="Validate" />
</form>
<?php
$sum=0;
if(isset($_POST['submit'])){
$sum+=1;
}
echo "sum = $sum";
?>
You can try below:
if(isset($_POST['name']) && strlen($_POST['name'])>0){
$sum+=1;
You have the code appending 1 to variable $sum
but your if statement is based on the name field being passed.
Not if the name field has any data in it.
So... you have made your code add 1 as long as name field is passed,
regardless if it has text input or not.
Also, you should reassign the varible to reset it.
+= should just be =
<form method="post" action="test.php">
//----------------------------- add empty value to input ------------
<input type="text" name="name" value="" placeholder="name"/><br />
<input type="submit" value="Validate" />
</form>
<?php
$sum=0;
if(isset($_POST['name'])){
$sum=1;
}
echo "sum = $sum";
?>

Getting a value from text input field, then displaying on POST

I'm trying to get a value from a form, then display it on posting of the form. I can get the value to appear in the second text field, once I have chosen an option using the Ajax Auto-Select, but how do I get that value shown stored into a variable for display on posting? This is what I have been trying -
if ($_POST['action'] == 'getentity') {
$value= $entity;
$content .= '<div>'.$value.' hello</div>';
}
<form method="post" action="?">
<input type="text" name="TownID_display" size="50" onkeyup="javascript:ajax_showOptions(this,\'getEntitiesByLetters\',event)">
<input type="text" name="TownID" id="TownID_display_hidden" value="'.$entity.'" />
<input type="hidden" name="action" value="getentity" />
<input type="submit" name="submit" value="Find"/>
Many thanks for any help.
Try
<input type="text" name="TownID" id="TownID_display_hidden" value="<?php $value = $entity; echo $entity; ?>" />
and its better to use like this
if ($_POST['action'] == 'getentity') {
$value= $_POST['TownID'];
$content .= '<div>'.$value.' hello</div>';
}
it should work.

PHP Delete not working as I would I like

Can someone help me. My delete code below works, but it's deleting the most recent Favorited file and not the specific file chosen. Here's the code:
while($row=$query->fetch())
{
$id=$row['id'];
$vid=$row['thread_id'];
$preview=$row['preview'];
$tt=$row['thread_title'];
$fav=$row['fav'];
$List.='<form action="" method="POST" id="postForm">
<div class="LISTT">'.$preview.'<br/><label id="pwords">'.$tt.'</label><br/>
<input type="submit" name="submit" value="Remove" id="DeleteButton"/>
</div></form>';
if(isset($_POST['submit']))
{
$query=$db->prepare("DELETE FROM favorite WHERE thread_id=:thread");
$query->execute(array(':thread'=>$vid));
}
}
You need to add a hidden form field that contains the Thread ID into your form, then read that back in your form handler, something like this:
while($row=$query->fetch())
{
$id=$row['id'];
$vid=$row['thread_id'];
$preview=$row['preview'];
$tt=$row['thread_title'];
$fav=$row['fav'];
$List.='<form action="" method="POST" id="postForm">
<div class="LISTT">'.$preview.'<br/><label id="pwords">'.$tt.'</label><br/>
<input type="hidden" name="thread" value="' . $vid . '" />
<input type="submit" name="submit" value="Remove" id="DeleteButton"/>
</div></form>';
if(isset($_POST['submit']))
{
$id = $_POST["thread"];
$query=$db->prepare("DELETE FROM favorite WHERE thread_id=:thread");
$query->execute(array(':thread'=>$id));
}
}
The reason for this is because you have the If statement in your while loop. The logic in the code you have given is to delete records when $_POST['submit'] is set. So it will follow the loop to delete the records and not a specific record.
You need to pass the id you want to delete to the user, as you are using form to do this, have a hidden field with the id.
if(isset($_POST['submit']))
{
$query=$db->prepare("DELETE FROM favorite WHERE thread_id=:thread");
$query->execute(array(':thread'=>$_POST['id']));
}
while($row=$query->fetch())
{
$id=$row['id'];
$vid=$row['thread_id'];
$preview=$row['preview'];
$tt=$row['thread_title'];
$fav=$row['fav'];
$List.='<form action="" method="POST" id="postForm">
<div class="LISTT">'.$preview.'<br/><label id="pwords">'.$tt.'</label><br/>
<input type="submit" name="submit" value="Remove" id="DeleteButton"/>
<input type="hidden" name="id" id="id" value="'.$id.'" />
</div></form>';
}

php or javascript Grab next array on button

Pulling simplexml and parsing them into php variables. I have a form with arrays in them. I want a button outside the form that will "essentially" go to the same form but with the next array number. IE:
<?
if( $xml = simplexml_load_file('my.xml') ) {
foreach( $xml as $SAVED_EXPORT) {
$mfg = $SAVED_EXPORT->productmanufacturer;
}
}
?>
<form id="myform" method="post" action="coderdb.php">
<input type="text" value="<? echo $mfg[0] ?>" name="MFG" />
<input type="submit" />
</form>
I'd like to have a button that says NEXT that when clicked it will pull up the next array ie. $mfg[1]. I believe the page would have to be reloaded which is fine. I read somewhere I may have to use $key but have never used and I am not exactly sure its what I need here.
You need some javascript use JQuery.
<script type="text/javascript">
$(function(){
var array = [];
<?
if( $xml = simplexml_load_file('my.xml') ) {
$i=0;
foreach( $xml as $SAVED_EXPORT) {
$mfg = $SAVED_EXPORT->productmanufacturer;
}
}
foreach($mgf as $key=$value) {
// if $key in not numeric then add iterator for this foreach
echo "array[$key]=$value";
}
?>
iterator = 0;
$('#nextExport').click(function(){
var theInput = $('#setExport');
// theInput.attr('val',array[iterator]);
theInput.val(array[iterator]);
if(iterator==array.length) {
iterator = -1;
}
iterator++;
});
});
</script>
<form id="myform" method="post" action="coderdb.php">
<input type="text" id="setExport" value="<? echo $mfg[0] ?> name="MFG" />
<input type="button" id="nextExport" value="Next Export" />
<input type="submit" />
</form>
I hope this helps. if something goes wrong check the syntax , logic is right.
You need a way of keeping track of which array index you are at because as of right now you only have it set to a static number 0. So if you add a hidden form you can have it post the value that you are currently at and then using PHP you can increment it before displaying the new form. Also your form should point to the PHP document that it is on.
<?
if( $xml = simplexml_load_file('my.xml') ) {
foreach( $xml as $SAVED_EXPORT) {
$mfg = $SAVED_EXPORT->productmanufacturer;
}
}
if(isset($_POST["index"])) $index = $_POST["index"] + 1;
else $index = 0;
?>
<form id="myform" method="post" action="coderdb.php">
<input type="hidden" value="<? echo $index ?>" name="index" />
<input type="text" value="<? echo $mfg[$index] ?>" name="MFG" />
<input type="submit" />
</form>

Categories