Jump to content

Recommended Posts

Hi,

I need to keep a variable value even after I refresh the page. For example: $cat = 2; I want $cat to equal to even after I press the refresh button! I am not sure how to do that. i 've looked at some example on the internet, but i can't get my variable to work.

Is there any way or any link that you suggest please?

Thanks,
Bee
Link to comment
https://forums.phpfreaks.com/topic/4973-keep-variable-value/
Share on other sites

the best way to handle this is with the use of session variables. for instance, on the following page, every time you refresh the page, it will hold the value you inserted until the session expires:
[code]
<?php
session_start();

if (isset($_POST['submit']))
  $_SESSION['name'] = $_POST['name'];

if (!isset($_SESSION['name']))
  echo "<p>Please enter a name!</p>\n";
else
  echo "<p>Name = \"$_SESSION[name]\"</p>\n";
?>

<form name='myForm' action='' method='post'>
Name: <input type='text' name='name' value='' />
<input type='submit' name='submit' value='Set Value' />
</form>
[/code]

hope this helps...

btw, i'm moving this to a more suitable topic area
Link to comment
https://forums.phpfreaks.com/topic/4973-keep-variable-value/#findComment-17526
Share on other sites

[!--quoteo(post=355055:date=Mar 14 2006, 04:19 PM:name=obsidian)--][div class=\'quotetop\']QUOTE(obsidian @ Mar 14 2006, 04:19 PM) [snapback]355055[/snapback][/div][div class=\'quotemain\'][!--quotec--]
the best way to handle this is with the use of session variables. for instance, on the following page, every time you refresh the page, it will hold the value you inserted until the session expires:
[code]
<?php
session_start();

if (isset($_POST['submit']))
  $_SESSION['name'] = $_POST['name'];

if (!isset($_SESSION['name']))
  echo "<p>Please enter a name!</p>\n";
else
  echo "<p>Name = \"$_SESSION[name]\"</p>\n";
?>

<form name='myForm' action='' method='post'>
Name: <input type='text' name='name' value='' />
<input type='submit' name='submit' value='Set Value' />
</form>
[/code]

hope this helps...

btw, i'm moving this to a more suitable topic area
[/quote]
Thanks for your help.

I have tried session variables, but it still does not work. I will try to explain better this time because the problem may be something else.
Basically, I have a combo box that displays choices to the user (e.g. books, computers...etc) each one of these items has got a value (e.g. books = 1, computers = 2...etc). Every time a user chooses one of these choices, the value of the selected choice is passed to a variable $category. For example: user selects books. then, $category = 1.

Then, $category is used as a condition to query the database. "SELECT * FROM table WHERE cat=" . $category .""
It works fine when I first run it, but the page uses some code for pagination. So it displays only two returned records at a time. When I run it, the first 2 records are displayed fine. But when I click next it promts me to select a category again. When I do, it just displays the same 2 records.

And $category loses its value.

i hope someone can understand what I mean and be able to help, I really need to get this working or I can't finish this project by the deadline.

Any help will be very much appreciated.
Bee
Link to comment
https://forums.phpfreaks.com/topic/4973-keep-variable-value/#findComment-17571
Share on other sites

[!--quoteo(post=355122:date=Mar 14 2006, 06:21 PM:name=keeB)--][div class=\'quotetop\']QUOTE(keeB @ Mar 14 2006, 06:21 PM) [snapback]355122[/snapback][/div][div class=\'quotemain\'][!--quotec--]
Oooooooooook. So..

Sessions are the way to go, keeping $category=1 in the URL is another way to go, <input type="hidden" name="category" value="books"> is another way to go..

It all depends on your approach..
[/quote]
Sorry. I did not quite understand your reply. Would you mind explaining please? An example will be great.
Link to comment
https://forums.phpfreaks.com/topic/4973-keep-variable-value/#findComment-17597
Share on other sites

Ok.. so say you have $_POST['category']; on processform.php (theoretical).

Here are the 3 ways to keep the value between pages that I mentioned Implimented..

Session..
[code]
<?
//Session Example.
session_start();

$_SESSION['category'] = $_POST['category']; //session variable registered.
?>
[/code]

As long as you have [b]session_start()[/b] on the top of EVERY page (before ANY code) you can use $_SESSION['category'] to retain the data you stored.

Input type..
[code]
<input type="hidden" name="category" value="<? print $_POST['category']; ?>">
[/code]

Put that anywhere in your page.. and if any forms are submitted on that page, the category data will pass through with it ([i]not recommended[/i])

Using $_GET:
Any and every URL you put, pass along category values through the link.. like
[code]<a href="somepage.php?category=<?=$_POST['category'];?>>some page</a>[/code]

Hope this was helpful, and realize that session variables are the easiest and most efficient way to retain data across multiple pages. :)

GOOD LUCK!



Link to comment
https://forums.phpfreaks.com/topic/4973-keep-variable-value/#findComment-17730
Share on other sites

[!--quoteo(post=355263:date=Mar 15 2006, 03:06 AM:name=keeB)--][div class=\'quotetop\']QUOTE(keeB @ Mar 15 2006, 03:06 AM) [snapback]355263[/snapback][/div][div class=\'quotemain\'][!--quotec--]
Ok.. so say you have $_POST['category']; on processform.php (theoretical).

Here are the 3 ways to keep the value between pages that I mentioned Implimented..

Session..
[code]
<?
//Session Example.
session_start();

$_SESSION['category'] = $_POST['category']; //session variable registered.
?>
[/code]

As long as you have [b]session_start()[/b] on the top of EVERY page (before ANY code) you can use $_SESSION['category'] to retain the data you stored.

Input type..
[code]
<input type="hidden" name="category" value="<? print $_POST['category']; ?>">
[/code]

Put that anywhere in your page.. and if any forms are submitted on that page, the category data will pass through with it ([i]not recommended[/i])

Using $_GET:
Any and every URL you put, pass along category values through the link.. like
[code]<a href="somepage.php?category=<?=$_POST['category'];?>>some page</a>[/code]

Hope this was helpful, and realize that session variables are the easiest and most efficient way to retain data across multiple pages. :)

GOOD LUCK!
[/quote]

Thanks for your suggestions. I tried using session variables; however, it did not work.
This is how my code looks like:
[code]<?php
    //start session
    session_start();
    
    //show table and header
    include("table_Upper_Part.php");
?>

    <form name="formCat" action="pagesTest.php" method="post">
        <div align = "left">
          <select name="cat">
            <option>Select a category</option>
            <option value='1' selected>Books</option>
            <option value='2'>Computers</option>
            <option value='3'>Bikes</option>
            <option value='4'>Music</option>
            <option value='5'>Software</option>
             <input type='submit' name = 'Search' value='Search' />
          </select>
        </div>
    </form>

<?php
    //if(!isset($_GET['Search'])){
       $_SESSION['$category'] = $_POST['cat'];
    //}

    include("connect.php");

    // If current page number, use it. if not, set one!
    if(!isset($_GET['page'])){
        $page = 1;
    } else {
        $page = $_GET['page'];
    }
    
    // Define the number of results per page
    $max_results = 2;
    
    // Figure out the limit for the query based
    // on the current page number.
    $from = (($page * $max_results) - $max_results);  
    
    //open form
    echo "<form name='checkbox1' method='post' action='basket.php'>";
    
    //select database
    $sql = "Select ProductID, Name, Description, PhotoName, Price, AmountAvailable From product WHERE CategoryID=".$_SESSION['$category']." LIMIT $from, $max_results";

    $result = mysql_query($sql);

    if ($result == false) {
        echo "<B>Please select a category.</B>";
    } else {
        $count = 1;
        $item = 1;
    while($row = mysql_fetch_array($result)){
                $item = $count;
                    
                echo "<table border='0' width = '778px' cellpadding='2'>";
                echo "<tr><td colspan=4  bgcolor='#FF9900'><B>Item: " . $count . "</B></td></tr>";
                
                echo "<tr><td width = '160px'>";
                
                echo "ProductID: " . 1000 . $row["ProductID"] . "<br>";
                echo "<img src=../images/".$row["PhotoName"].">" . "</font><br>";
                echo "<B>Price on shop:</B> <S><B>£" . $row["Price"] . "</B></S><br>";
                echo "<B>Our price: £" . $row["AmountAvailable"] . "<B>";
                
                echo "</td><td>";
                echo " Name: <font color='#0000FF'> " . $row["Name"] . "</font><br><br>";
                echo " Description: " . $row["Description"] . "<br>";                         
                
                echo "<td width='10px'></td>";
                
                echo "</td><td width = '50px' cellpadding='2'>";  
                echo "<p>Add to Basket <p><input type='checkbox' name='".$checkOut.$item."'>";  
                echo "</td></tr>";
                echo "</table> <br>";
                
                
                //carry the value to the next page
                $_SESSION['$loop'] = $item;
                $_SESSION['$productID'][$item] = $row["ProductID"];
                $_SESSION['name'][$item] = $row["Name"];
                $_SESSION['priceOnShop'][$item] = $row["Price"];
                $_SESSION['ourPrice'][$item] = $row["AmountAvailable"];
                
                $count++;  
            }
            
            echo "<input type='submit' value='Checkout' name='submit'>";
            echo "</form> ";
        }
    
    // Figure out the total number of results in DB:
    $argument = mysql_query("SELECT COUNT(*) as Num FROM product WHERE CategoryID=".$_SESSION['$category']."");
  
    $total_results = mysql_result($argument, 0);
    
    // Figure out the total number of pages. Always round up using ceil()
    $total_pages = ceil($total_results / $max_results);
    
    // Build Page Number Hyperlinks
    echo "<center>Select a Page<br />";
    
    // Build Previous Link
    if($page > 1){
        $prev = ($page - 1);
        echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$prev\"><<Previous</a> ";
    }
    
    for($i = 1; $i <= $total_pages; $i++){
        if(($page) == $i){
            echo "$i ";
            } else {
                echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$i\">$i</a> ";
        }
    }
    
    // Build Next Link
    if($page < $total_pages){
        $next = ($page + 1);
        echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$next\">Next>></a>";
    }
    echo "</center>";
    
    //close connection
    mysql_close($link);
    
    //show table lower part
    include("table_Lower_Part.php")
?>[/code]

And this is a demo of the problem:

[a href=\"http://www.frag4.net/test/studentbuyer/php/pagesTest.php\" target=\"_blank\"]demo[/a]

Any help will be very very much appreciated.

Bee
Link to comment
https://forums.phpfreaks.com/topic/4973-keep-variable-value/#findComment-17786
Share on other sites

[!--quoteo(post=355048:date=Mar 14 2006, 03:58 PM:name=Bee)--][div class=\'quotetop\']QUOTE(Bee @ Mar 14 2006, 03:58 PM) [snapback]355048[/snapback][/div][div class=\'quotemain\'][!--quotec--]
Hi,

I need to keep a variable value even after I refresh the page. For example: $cat = 2; I want $cat to equal two even after I press the refresh button! I am not sure how to do that. i 've looked at some example on the internet, but i can't get my variable to work.

Is there any way or any link that you suggest please?

Thanks,
Bee
[/quote]
I am still stuck guys! Can any body help please!
Link to comment
https://forums.phpfreaks.com/topic/4973-keep-variable-value/#findComment-18173
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.