Reputation: 1600
I have a bunch of data in an array which has been collected in a session. I am able to print_r this and show all the contents but I am struggling to show the product name, id, image etc.
I am showing the using:
<?php
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
?>
It prints out everything I need but not in the format I require. So I know it is collecting my data and storing it in the array. I have set the data in another files like so:
if (isset($_POST['Submit'])) {
$_SESSION['product_img'][] = $_POST['product_img'];
$_SESSION['product_id'][] = $_POST['product_id'];
$_SESSION['product_name'][] = $_POST['product_name'];
$_SESSION['product_price'][] = $_POST['product_price'];
$_SESSION['product_sku'][] = $_POST['product_sku'];
$_SESSION['product_description'][] = $_POST['product_description'];
}
And it is all of the above I want to output.
Upvotes: 0
Views: 73
Reputation: 40648
**Either you stick with your proposal : $_SESSION['...'][]
**
if (isset($_POST['Submit'])) {
$_SESSION['product_img'][] = $_POST['product_img'];
$_SESSION['product_id'][] = $_POST['product_id'];
$_SESSION['product_name'][] = $_POST['product_name'];
$_SESSION['product_price'][] = $_POST['product_price'];
$_SESSION['product_sku'][] = $_POST['product_sku'];
$_SESSION['product_description'][] = $_POST['product_description'];
}
and format it like so:
foreach($_SESSION as $elements)
{
foreach($elements as $element) {
echo $element . '<br />';
}
}
Or use this other method:
if (isset($_POST['Submit'])) {
$_SESSION['product_img'] = $_POST['product_img'];
$_SESSION['product_id'] = $_POST['product_id'];
$_SESSION['product_name'] = $_POST['product_name'];
$_SESSION['product_price'] = $_POST['product_price'];
$_SESSION['product_sku'] = $_POST['product_sku'];
$_SESSION['product_description'] = $_POST['product_description'];
}
and format it like so:
foreach($_SESSION as $element)
{
echo $element . '<br />';
}
Upvotes: 1
Reputation:
A simple way to output this as HTML is to use a foreach loop, which goes through each item in the array.
To make things easier, I would suggest changing your POST code so that each item is a single array, like so.
if (isset($_POST['Submit'])) {
$_SESSION['products'][] = array(
'img' => $_POST['product_img'],
'id' => $_POST['product_id'],
'name' => $_POST['product_name'],
'price' => $_POST['product_price'],
'sku' => $_POST['product_sku'],
'description' => $_POST['product_description']
);
}
Now you can iterate through $_SESSION['products']
and get the information for each product in the session. For example:
foreach ($_SESSION['products'] as $product) {
$name = $product['name'];
$id = $product['id'];
$price = $product['price'];
$img = $product['img'];
$sku = $product['sku'];
$description = $product['description'];
echo "<h1>Product: $name</h1>";
echo "<p>Price: $price | ID: $id</p>";
echo "<img src='$img'>";
echo "<p>$description</p>";
echo "<hr />";
}
Upvotes: 1