Jump to content

on button click, increment variable


farahZ
Go to solution Solved by DaveyK,

Recommended Posts

hello, what am trying to do is that to allow the user choose from a dropdown list items (item by item) and add each, constantly viewing the added items. the added items must be saved in an array (foodSelected).

the problem i am facing is with creating is with creating a variable, and incrementing this variable by one each item the user adds an item!!
i want that counter for several reason:

- array printing

- sending the array items to the database

 

i read in the forums something about $_session variables, i tried to implement it.. but still got errors

thats the code i wrote, its a calorie counter.. i will appreciate any help

 

 

<?php session_start(); ?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Calorie Counter</title>
</head>
    
<body>
<p>It's Breakfast </p>
<p>
<form action="" method="post">
  <p>
    <select name="foodType" id="foodType">
      <option selected="selected">Labneh</option>
      <option>Cucumber</option>
      <option>Tomato</option>
      <option>Lettuce</option>
      <option>Cucumber Pickles</option>
      <option>Olive Oil</option>
      <option>Cucumber without peal</option>
      <option>Olive Black</option>
      <option>Olive Green</option>
    </select>
    <input name="submit" type="submit" id="submit"  value="add">
  </p>
</p>
</form>
<?php
if (isset($_POST['submit']))
{
     chosenItems();
 
}
 
$_SESSION['counter'] = (!$_SESSION['counter']) ? 0 : $_SESSION['counter'];
if($_POST['add']) {
 $_SESSION['submit']++;
}
function chosenItems()
{
$foodSelected[$counter]= $_REQUEST["foodType"];
echo "food added: ", "<BR>";
print_r($foodSelected);
}
?>
 
</body>
</html>

 

Link to comment
Share on other sites

Well, even though I dont really understand, start here:

 

1) All your code should be in code tags.

[code]YOUR CODE[/code]

2)  All you logic should be above your HTML. Right now you are not consistent.

<?php session_start(); 

if (isset($_POST['submit']))
{
     chosenItems();
 
}
 
$_SESSION['counter'] = (!$_SESSION['counter']) ? 0 : $_SESSION['counter'];
if($_POST['add']) {
 $_SESSION['submit']++;
}
function chosenItems()
{
$foodSelected[$counter]= $_REQUEST["foodType"];
echo "food added: ", "<BR>";
print_r($foodSelected);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Calorie Counter</title>
</head>
    
<body>
<p>It's Breakfast </p>
<p>
<form action="" method="post">
  <p>
    <select name="foodType" id="foodType">
      <option selected="selected">Labneh</option>
      <option>Cucumber</option>
      <option>Tomato</option>
      <option>Lettuce</option>
      <option>Cucumber Pickles</option>
      <option>Olive Oil</option>
      <option>Cucumber without peal</option>
      <option>Olive Black</option>
      <option>Olive Green</option>
    </select>
    <input name="submit" type="submit" id="submit"  value="add">
  </p>
</p>
</form>
</body>
</html>

Thats a START. Its still far from done.

 

3) Third, you have two if statements on the _POST. One for "submit" and another for "add". The "add" will NEVER run, as the name for the submit button is "submit" and not "add" (the value is add, but thats just for the users). One might argue if its even smart to put a conditional on the submit. You can also check if $_POST["foodType"] is empty or not and go from there.

 

4) Not as important, but your HTML nesting is faulty.

<p>
  <form action="" method="post">
    <p>
      ...........
    </p>
  </p>
</form>

5) I STRONGLY urge you to use value attributes for HTML <option> tags

<option value="<SOME_VALUE>">SOME_NAME</option>

This is the part that PHP reads (the "value").

 

6) In the function, you are reading $_REQUEST. Why dont you just pass it as a value?!

function chosenItems($foodType)
{
$foodSelected[$counter]= $foodType;
echo "food added: ", "<BR>";
print_r($foodSelected);
}

Also, $counter will an undefined index error since it doesnt exist anywhere.

 

 

That covers the general part of your script. Now what do you actually wish to achieve?

Edited by DaveyK
Link to comment
Share on other sites

hello, your reply is much appreciated  :happy-04: 
I corrected everything you said.. i'm new to all this world

 

i will make myself clearer.. the calorie counter idea is that the user must add to the list all items from the dropdown list he wants by choosing the food item and clicking add. upon each 'add' click, all items chosen are continuously printed. when  he is done adding, he must press submit for the calculation of the calories to take place.(count the calories of the food he chose)

 

here is the corrected code

 

 
<?php session_start(); ?>
<?php
if (isset($_POST['submit']))
{
     chosenItems();
}
 
$_SESSION['counter'] = (!$_SESSION['counter']) ? 0 : $_SESSION['counter'];
if($_POST['submit']) {
 $_SESSION['counter']++;
}
function chosenItems()
{
$foodSelected[
$_SESSION['counter']]= $_REQUEST["foodType"];
echo "food added: ", $_SESSION['counter'], "<BR>";
 
for ($i=0; $i<$_SESSION['counter']; $i++)
echo $foodSelected[$i], "<BR>";
}
?>
<input name="Submit" type="submit" value="Submit" />
<?
if($_POST['submit']) {
 unset($_SESSION['counter']);
}
echo "session destroyed";
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Calorie Counter</title>
</head>
    
<body>
<p>It's Breakfast </p>
<p>
<form action="" method="post">
  <p>Keep on adding items:</p>
  <p> when you are done, click submit</p>
  <p>
    <select name="foodType" id="foodType">
      <option value="Labneh" selected="selected">Labneh - لبنة</option>
      <option value="Cucumber">Cucumber-خيار</option>
      <option value="Tomato">Tomato-بندورة</option>
      <option value="Lettuce">Lettuce-خس</option>
      <option value="Cucumber Pickles">Cucumber Pickles -كبيس خيار</option>
      <option value="Olive Oil">Olive Oil- زيت زيتون</option>
      <option value="Cucumber without peal">Cucumber without peal - خياره مقشرة</option>
      <option value="Olive Black">Olive Black- زيتون أسود</option>
      <option value="Olive Green">Olive Green - زيتون اخضر</option>
    </select>
    <input name="submit" type="submit" id="submit"  value="add">
  </p>
 
</form>
 
</body>
</html>
Link to comment
Share on other sites

ya i know the multiple choosing

i dont want to use because i will be adding more food items later reaching about 100
anyway my problem is with the printing, added items are not printed, there's an error

Link to comment
Share on other sites

I get that, I just want to make sure there is already something that does. HOWEVER, since you choose to do it like this, lets roll :P

What you need first a good starting point. This is your script without any backend to it. If you click "add", nothing happens.

<?php 

session_start();

?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Calorie Counter</title>
</head>
<body>
  <p>It's Breakfast </p>
  <p>
    <form action="" method="post">
      <p>Keep on adding items:</p>
      <p> when you are done, click submit</p>
      <p>
        <select name="foodType" id="foodType">
          <option value="Labneh" selected="selected">Labneh - ????</option>
          <option value="Cucumber">Cucumber-????</option>
          <option value="Tomato">Tomato-??????</option>
          <option value="Lettuce">Lettuce-??</option>
          <option value="Cucumber Pickles">Cucumber Pickles -???? ????</option>
          <option value="Olive Oil">Olive Oil- ??? ?????</option>
          <option value="Cucumber without peal">Cucumber without peal - ????? ?????</option>
          <option value="Olive Black">Olive Black- ????? ????</option>
          <option value="Olive Green">Olive Green - ????? ????</option>
        </select>
        <input name="add" type="submit" id="add"  value="add">
      </p>
      <input name="submit" type="submit" id="submit" value="Submit">
    </form>
  </p>
</body>
</html>

Having a clean starting up is also important. You want two functionalities in the script:

 

- Clicking add generates a list of the products someone has consumed

- Clicking submit sends this list to somewhere

 

You want to store this in a session, but first start off with capturing the data:

if (isset($_POST['add']))
{
  if (empty($_POST['foodType']))
  {
    echo 'You need to select some food!'; 
  }
  else
  {
    if (!isset($_SESSION['foodTypes']))
    {
      $_SESSION['foodTypes'] = array();
    }

    $_SESSION['foodTypes'][] = $_POST['foodType'];
  }

  echo '<pre>' . print_r($_SESSION['foodTypes'], true) . '</pre>';
}

Naturally, since this is processing code  this is placed ABOVE the html, underneath the session_start().

 

If you now select something, the session should grow.

 

EDIT: fixed typos. Sorry.

Edited by DaveyK
Link to comment
Share on other sites

ya creating an array session is better than the counter

does it show you the printed array or ur not testing it?

 

 

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php session_start(); ?>
<?php
if (isset($_POST['add']))
{
  if (empty($_POST['foodType']))
  {
    echo 'You need to select some food!'; 
  }
  else
  {
    if (!isset($_SESSION['foodTypes']))
    {
      $_SESSION['foodTypes'] = array();
    }
 
    $_SESSION['foodTypes'][] = $_POST['foodType'];
  }
 
  echo '<pre>' . print_r($_SESSION['foodTypes'], true) . '</pre>';
}
?>
<input name="Submit" type="submit" value="Submit" />
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Calorie Counter</title>
</head>
    
<body>
<p>It's Breakfast </p>
<p>
<form action="" method="post">
  <p>Keep on adding items:</p>
  <p> when you are done, click submit</p>
  <p>
    <select name="foodType" size="1" id="foodType">
      <option value="Labneh" selected="selected">Labneh - لبنة</option>
      <option value="Cucumber">Cucumber-خيار</option>
      <option value="Tomato">Tomato-بندورة</option>
      <option value="Lettuce">Lettuce-خس</option>
      <option value="Cucumber Pickles">Cucumber Pickles -كبيس خيار</option>
      <option value="Olive Oil">Olive Oil- زيت زيتون</option>
      <option value="Cucumber without peal">Cucumber without peal - خياره مقشرة</option>
      <option value="Olive Black">Olive Black- زيتون أسود</option>
      <option value="Olive Green">Olive Green - زيتون اخضر</option>
    </select>
    <input name="submit" type="submit" id="submit"  value="add">
  </p>
 
</form>
 
</body>
</html>
Link to comment
Share on other sites

  • Solution

I have this code so far, and it appears to work fine.

<?php

session_start();

if (isset($_POST['add']))
{
  // check if an option has been selected
  if (empty($_POST['foodType']))
  {
    echo 'You need to select some food!'; 
  }
  else
  {
    if (!isset($_SESSION['foodTypes']))
    {
	  // if the session is not yet created, create it now
      $_SESSION['foodTypes'] = array();
    }
    
	// add the selected food item to total food array
    $_SESSION['foodTypes'][] = $_POST['foodType'];
  }

  // display the current food list (in a really ugly PHP way)
  echo '<pre>' . print_r($_SESSION['foodTypes'], true) . '</pre>';
} 
else if (isset($_POST['submit']))
{
  // check if the session exists, or if its empty
  if (!isset($_SESSION['foodTypes']) || empty($_SESSION['foodTypes']))
  {
    echo 'No food in the list to submit!';
  }
  else
  {
    // session exists and has content
    // process the array list here.
	
	
	// after the processing, empty the session
    $_SESSION['foodTypes'] = array();
  }
}

?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Calorie Counter</title>
</head>
<body>
  <p>It's Breakfast </p>
  <p>
    <form action="" method="post">
      <p>Keep on adding items:</p>
      <p> when you are done, click submit</p>
      <p>
        <select name="foodType" id="foodType">
          <option value="Labneh" selected="selected">Labneh - ????</option>
          <option value="Cucumber">Cucumber-????</option>
          <option value="Tomato">Tomato-??????</option>
          <option value="Lettuce">Lettuce-??</option>
          <option value="Cucumber Pickles">Cucumber Pickles -???? ????</option>
          <option value="Olive Oil">Olive Oil- ??? ?????</option>
          <option value="Cucumber without peal">Cucumber without peal - ????? ?????</option>
          <option value="Olive Black">Olive Black- ????? ????</option>
          <option value="Olive Green">Olive Green - ????? ????</option>
        </select>
        <input name="add" type="submit" id="add"  value="add">
      </p>
      <input name="submit" type="submit" id="submit" value="Submit">
    </form>
  </p>
</body>
</html>

I somehow lost the special characters, but this works. It allows duplicated in the array and it doesnt do much on submit.

 

How does it work on your end?

Link to comment
Share on other sites

to prevent duplicates, you would test if any submitted food item is already in the array before trying to add it. in fact, for a nicer user experience, you could dynamically build the <option></option> list by checking if each item has already been selected and either not output it in the <option></option> list or make it disabled in the <option></option> list.

Link to comment
Share on other sites

can i print it such way?? not using print_f function

i prefer knowing the array count for later usage .. i.e. sending array to the database (mysql/xampp)

 

 
// display the current food list (in a really ugly PHP way)
  echo "food added: ", "<BR>";
 
for ($i=0; $i<count($_SESSION['foodTypes']); $i++)
echo $_SESSION['foodTypes'][i], "<BR>";
Link to comment
Share on other sites

Yes, you can do it. You can use a for() loop as you are using now, but I would suggest a foreach() which is much easier.

<?php

foreach ($_SESSION['foodTypes'] as $food)
{
  echo $food . '<br>';
}

?>

Thats basically what gets it done.

 

Also, you STILL need to think about what you want to do with the data the moment you use the submit (the actual submit, not the add). That does not work at all right now.

 

EDIT: if you want to know if the item is taken, and also if you want to make sure you dont have duplicates in your $_SESSION['foodTypes'] array, you need to use the in_array() PHP function. To keep duplicates from being added to the array:

(...)
  else
  {
    if (!isset($_SESSION['foodTypes']))
    {
       // if the session is not yet created, create it now
       $_SESSION['foodTypes'] = array();
    }

    // check to see if the newly added food type is not already in the array
    if (in_array($_POST['foodType'], $_SESSION['foodType']) === false) 
    {
      // The selected food item is not in the array
      // add the selected food item to total food array
      $_SESSION['foodTypes'][] = $_POST['foodType'];
    }
  }
(...)

Now if you also want to keep the selected food items from showing up in the <select> you need to do a bit more work.

 

- First you need to store the items inside the select in an array. If you fetch them from a database, this is already the case.

- Then you should use a foreach loop to display the <option>s (at this point you should have exactly the same HTML as you have right now, but dynamically generated by PHP)

- Now for hiding certain items, you need to use the in_array() function to see if the current item in the foreach loop is also in the foodType session variable. If that is true, dont echo anything. If it is false, show the food as an option.

 

I think that pretty much describes it. You need to convert this:

<select name="foodType" id="foodType">
          <option value="Labneh" selected="selected">Labneh - ????</option>
          <option value="Cucumber">Cucumber-????</option>
          <option value="Tomato">Tomato-??????</option>
          <option value="Lettuce">Lettuce-??</option>
          <option value="Cucumber Pickles">Cucumber Pickles -???? ????</option>
          <option value="Olive Oil">Olive Oil- ??? ?????</option>
          <option value="Cucumber without peal">Cucumber without peal - ????? ?????</option>
          <option value="Olive Black">Olive Black- ????? ????</option>
          <option value="Olive Green">Olive Green - ????? ????</option>
        </select>

into something like this:

<select name="foodType" id="foodType">
  <?php
  
  foreach ( .... )
  {
    // do something here
  }

  ?>
</select>

You should be able to make it work from what I described here.

Edited by DaveyK
Link to comment
Share on other sites

hey again
i am trying now to calculate the total calories of the food added by the user
each food type has a corresponding calorie value in a table in mysql (xampp)
thats what am doing:

else if (isset($_POST['Calculate Calories']))
{
// Create connection
$con=mysqli_connect("localhost","root","","inshapewebsite");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}  
foreach ($_SESSION['foodTypes'] as $food)
{
$query = "SELECT  Calories FROM food where Food='$food'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
echo $row['Calories'];
//$calories=$calories + $row['Calories'];
}
}
//echo 'The amount of Calories is: ' . $calories;
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.