How to store select box value in a session array variable without using multiple?

1k views Asked by At

Maybe its a duplicate question but i couldn't find any answer reg. I have a select box whose value is to be stored in session array variable. I tried but not working.

Here is the code: form1.php

<form name="input" action="result.php" method="post">
  <input type="text" name="product" />
  <input type="text" name="name1" />
  <select name="strtpnt" id="strtpnt"  class="inp_bx">  
    <option>-Select-</option>
    <option value="1">Cat</option>
    <option value="2">bat</option>
    <option value="3">rat</option>
    <option value="4">mat</option>
  </select>
  <input type="submit" value="Add" />
</form> 

Here is result.php code:

<?php
session_start();
$strtpnt1 = array();
if(isset($_POST['product'])) {
    $products = isset($_SESSION['products']) ? $_SESSION['products'] : array();
    $products[] = $_POST['product'];
    $_SESSION['products'] = $products;
}
if(isset($_POST['name1'])) {
    $name = isset($_SESSION['name']) ? $_SESSION['name'] : array();
    $name[] = $_POST['name1'];
    $_SESSION['name'] = $name;
}
if(isset($_POST['strtpnt'])) {
    $strtpnt1 = isset($_SESSION['strtpnt1']) ? $_SESSION['strtpnt1'] :array();
    $strtpnt1[] = $_POST['strtpnt'];
    $_SESSION['strtpnt1'][] = $strtpnt1;
}
print_r($_SESSION['products']);
print_r($_SESSION['name']);
print_r($_SESSION['strtpnt1']);
?>

The input box values are stored in session arrray variable but not the select box .

Array ( [0] => 2 [1] => Array ( [0] => 2 ) [2] => Array ( [0] => 2 ) [3] => Array ( [0] => 2 [1] => Array ( [0] => 2 ) [2] => Array ( [0] => 2 ) [3] => Array ( [0] => 2 ) ) )

I want to get the select box value as:

 Array ( [0] => ddd [1] => ddd [2] => sss [3] => sss [4] => ss [5] => ss [6] => ttt )

Any suggestions or help regarding this is more welcome.

2

There are 2 answers

2
Nitin On

Please try this [ considering your discussion wiht kRiz ]

if(isset($_POST['strtpnt'])) {
    $strtpnt1 = isset($_SESSION['strtpnt1']) ? $_SESSION['strtpnt1'] :array();

    if(!array_key_exists($_POST['strtpnt'],$_SESSION['strtpnt1']))
    {
        $strtpnt1 = array_push($strtpnt1,$_POST['strtpnt']);
    }

    $_SESSION['strtpnt1'] = $strtpnt1;
}
5
kRiZ On

Try changing this:

$_SESSION['strtpnt1'][] = $strtpnt1;

to this:

$_SESSION['strtpnt1'] = $strtpnt1;

UPDATE:

if(isset($_POST['strtpnt'])) {
    $strtpnt1 = isset($_SESSION['strtpnt1']) ? $_SESSION['strtpnt1'] : array();
    array_push($strtpnt1, $_POST['strtpnt']);
    $_SESSION['strtpnt1'] = $strtpnt1;
}

Edit: Directly push the value from $_POST without storing in any array.

array_push() is used to append values to an array.