Jump to content

how to store multidimensional sessions


jasonc

Recommended Posts

I wish to know how I can store the VALUE given below in a session variable under the ID number.

 

How can I do this correctly ?

 

Also so it keeps the previously stored data.

<?
session_start();

echo("....<br>");
if ($_POST) {
foreach($_POST as $key => $val) {
	if (is_numeric($val)) {
	echo("key=".$key.". val=".$val.".<br />");
	// add/replace to sessions variable.
	$_SESSION['cart'][$key] = $val;
	}
}
}
echo("....<br>");

foreach($_SESSION['cart'] as $key => $val) {
	if (is_numeric($val)) {
	echo("key=".$key.". val=".$val.".<br />");
	}
}
echo("....");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>

<form action="" method="post">
ID Number<input name="id" type="text" value=""><br>
Value<input name="value" type="text" value=""><br>
<input name="submit" type="submit" value="submit">
</form>

</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/239717-how-to-store-multidimensional-sessions/
Share on other sites

There is no need for a loop. You can add the entered values into your $_SESSION['cart'] array like this

<?php
session_start();

// check that the form has been submited
if (isset($_POST['submit']))
{
    // check that the entered id is a number
    if(is_numeric($_POST['id'])
    {
        // get the id number the user typed in
        $id    = $_POST['id'];
        // get the value the user typed in
        $value = $_POST['value'];

        // use $id as the key
        //     $value as the value.
       $_SESSION['cart'][$id] = $value;
    }
}

// output the contents of the $_SESSION array
echo '<pre>' . print_r($_SESSION, true) . '</pre>';
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>

<form action="" method="post">
ID Number<input name="id" type="text" value=""><br>
Value<input name="value" type="text" value=""><br>
<input name="submit" type="submit" value="submit">
</form>

</body>
</html>

For each id number you enter, it'll add it to the $_SESSION['cart'] array. The value will be tied to the id.

how do i remove one of them should someone enter '0'  zero

You'd do this within the if statement.

Change

    if(is_numeric($_POST['id'])

To

if(is_numeric($_POST['id'])) && ($_POST['id'] != '0' && $_POST['value'] != '0'))

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.