Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store variable values over multiple page loads

Tags:

php

I'm making a php script that stores 3 arrays: $images, $urls, $titles based on the input data of the form within the php file.

I want to print the values of these arrays in the first part of the page and then to pre-fill the form's input fields with the value of the arrays. Also when a user modifies an input field and clicks on "Save" the page should reload with the modfied version.

My problem is that on each call of the php file in a browser the value of the variables gets deleted. Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?

<?php
//save the arrays with the form data
$images = array($_POST["i0"],$_POST["i1"],$_POST["i2"],$_POST["i3"]);
$urls = array($_POST["u0"],$_POST["u1"],$_POST["u2"],$_POST["u3"]);
$titles = array($_POST["t0"],$_POST["t1"],$_POST["t2"],$_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
   echo"<div>
            <input name='i".$x."' type='text' value='".$images[$x]."'>
            <input name='u".$x."' type='text' value='".$urls[$x]."'>
            <input name='t".$x."' type='text' value='".$titles[$x]."'>";
       $x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
like image 360
Bogdan Avatar asked Nov 01 '11 10:11

Bogdan


People also ask

Can you store variables in an array?

A variable array is a group of variables stored under the same name but with different index values. In the array declaration and initialization example below, you can think of the index value as the position of a specific variable in the list.

What is storing a value in a variable called?

r-value: It refers to the data value that is stored at some address in memory.


2 Answers

Store the variables in a PHP session.

session_start();
$_SESSION['images'] = $images;

Then on next (or any other) page, you can retrieve the values as:

session_start();
$images = $_SESSION['images'];
like image 154
Vikk Avatar answered Oct 10 '22 04:10

Vikk


Changing the scope of the variables to a larger scope, might do the trick. Also, check if you have a post request before updating the values.

<?php
    if(sizeof($_POST) >0)
    {
      //UPDATE VALUES
    }
?>
like image 39
abhinav Avatar answered Oct 10 '22 04:10

abhinav