Jump to content

sessions, counter problem !


farahZ

Recommended Posts

hey,i dont know if my work is correct or no !

I am trying to create several session arrays, and fill them with user inputs

the common between the session arrays will be the counter ($c)

then using the counter, with the help of a for loop, i want to print the arrays !!

here is the code.. please have a look, any mistake or notice please inform me

 

 

<?php
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']) || !isset($_SESSION['Quantity']) || !isset($_SESSION['Calories']) || !isset($_SESSION['Unit']))
    {
 // if the session is not yet created, create it now
    $_SESSION['foodTypes'] = array();
$_SESSION['Quantity']= array ();
$_SESSION['Calories']=array();
$_SESSION['Unit']=array();
$c=0;
    }
    // check to see if the newly added food type is not already in the array
    if (in_array($_POST['foodType'], $_SESSION['foodTypes']) === false) 
    {
      // The selected food item is not in the array
      // add the selected food item to total food array
      $_SESSION['foodTypes'][$c] = $_POST['foodType'];
 $_SESSION['Quantity'][$c]= $_POST['fooDquantity'];
 $_SESSION['Unit'][$c]=$_POST['quantityValue'];
 echo $c;
 $c++;
//$foodQuan = $_POST['fooDquantity'];
// $foodVal=$_POST['quantityValue'];
//  $_SESSION['Quantity'][$c]= $foodQuan ." ". $foodVal;
    }
  }
 
} 
 

function print_array(){
if(!empty($_SESSION['foodTypes'])){
echo '<br>'. '<br>'. "Food Added:" . '<br>';
 // display the current food list
 
 for ($i =0; $i <=$c; $i++)
 {
 $fcal=getCalories($_SESSION['foodTypes'][i], $_SESSION['Quantity'][i], $_SESSION['Unit'][i]);
 echo $_SESSION['foodTypes'][i] . '  ' . $fcal . ' calories' .'<br>';
 $calories= $calories + $fcal;
 }
/* $_SESSION['Calories']=$fcal;
 foreach ($_SESSION['foodTypes'] as $food)
{
$fcal=getCalories($food, $foodQuan, $foodVal);
echo $food . '  ' . $fcal . ' calories' .'<br>';
$calories= $calories + $fcal;
//$calories= calculate($_SESSION['foodTypes']);
}
*/
echo 'The amount of Calories is now: ' . $calories, "\n";
createDropdown($_SESSION['foodTypes']);
}
?>
}
Link to comment
Share on other sites

You do stuff with $c but it never comes from the session or gets saved into the session. It starts at 0 every time.

 

You don't even need it though if you moved your data around to something a little better. Try a structure like

$_SESSION[food] = array(
	array(
		[type] =>
		[quantity] =>
		[calories] =>
		[unit] =>
	),
	array(
		[type] =>
		[quantity] =>
		[calories] =>
		[unit] =>
	),
	array(
		[type] =>
		[quantity] =>
		[calories] =>
		[unit] =>
	),
	...
)
If the food type is a string you can use it as array keys too so it's easier to tell if one has been... "used", or whatever... yet.
Link to comment
Share on other sites

i think i got your idea

but how will be able to call them afterwards for printing? because each foodtype has its own type, quantity and unit..

 

thats the neat code.. i really dont know if i'm able to make myself clear

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']) || !isset($_SESSION['Quantity']) || !isset($_SESSION['Unit']))
    {
 // if the session is not yet created, create it now
    $_SESSION['foodTypes'] = array();
$_SESSION['Quantity']= array ();
$_SESSION['Unit']=array();
$c=0;
    }
    // check to see if the newly added food type is not already in the array
    if (in_array($_POST['foodType'], $_SESSION['foodTypes']) === false) 
    {
      // The selected food item is not in the array
      // add the selected food item to total food array
      $_SESSION['foodTypes'][$c] = $_POST['foodType'];
 $_SESSION['Quantity'][$c]= $_POST['fooDquantity'];
 $_SESSION['Unit'][$c]=$_POST['quantityValue'];
 $c++;
    }
  }
 
} 
 
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
{
$con=mysqli_connect("localhost","root","","inshapewebsite");
if (mysqli_connect_errno($con))
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}  
 
$date=date("Y-m-d");
for ($i =0; $i <=$c; $i++)
{
$cal=getCalories($_SESSION['foodTypes'][i], $_SESSION['Quantity'][i], $_SESSION['Unit'][i]);
$sql="";
$clid=$_SESSION['views'][0];
$q= $_SESSION['Quantity'][i]. ' ' . $_SESSION['Unit'][i];
$food=$_SESSION['foodTypes'][i];
 
$sql = "INSERT INTO fooddiary (ID, Date, DayTime, Food, Quantity, Calories)
VALUES ('$clid', '$date', 'Lunch', '$food', '$q', $cal)";
var_dump($sql);
$result = mysqli_query($con, $sql) or die(mysqli_error());
}
 
$total= calculate($_SESSION['foodTypes'], $_SESSION['Quantity'], $_SESSION['Unit']);
echo 'The total calories submitted is ' . $total, "\n"; 
unset($_SESSION['foodTypes']);
mysqli_close($con);
}
 
function calculate($foodTypes, $Quantity, $Unit){
$calories = 0;
for ($i =0; $i <=$c; $i++)
 {
 $fcal=getCalories($_SESSION['foodTypes'][i], $_SESSION['Quantity'][i], $_SESSION['Unit'][i]);
 $calories= $calories + $fcal;
 }
return $calories;
}
 
function getCalories($food, $foodQuan, $foodVal)
{
// Create connection
$con=mysqli_connect("localhost","root","","inshapewebsite");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} 
$query = "SELECT Size, Calories FROM food where Food='$food' ";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
 
if($foodVal=='Portion')
{
$fcal=$foodQuan*$row['Calories'];
}
else if($foodVal=='Grams')
{
$fcal=($foodQuan*$row['Calories'])/$row['Size'];
}
else $fcal=$row['Calories'];
return $fcal;
}
Link to comment
Share on other sites

by using three arrays, you are making three times too much code.

 

do this -

 

If the food type is a string you can use it as array keys too so it's easier to tell if one has been... "used", or whatever... yet.

 

 

and all your code will be simple -

if (isset($_POST['add'])){
    if (empty($_POST['foodType'])){
        echo 'You need to select some food!';
    } else {
        if(!isset($_SESSION['food'][$_POST['foodType']])){
            $_SESSION['food'][$_POST['foodType']] = array('Quantity' => $_POST['fooDquantity'], 'Unit' => $_POST['quantityValue']);
        }
    }
}
Link to comment
Share on other sites

you would just use a foreach(){} loop.

 

 

for your database query to get the calorie information, you should not run a query inside of a loop. since the foodTypes are the keys of the $_SESSION['food'] array, just get all the keys and run one query to get all the rows you need -

$types = implode("','",array_keys($_SESSION['food']));
$query = "SELECT Food, Size, Calories FROM food where Food IN('$types')";
$result = mysqli_query($con,$query);
$calories = array();
while($row = mysqli_fetch_assoc($result)){
    $calories[$row['Food']] = $row; // store the rows using the Food as the key so that this information can be easily accessed when needed
}

as you loop over the $_SESSION['food'] array, the key (foodType) from this array can be used to get the corresponding calories/size information from the $calories array that was formed in the above code.

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.