Jump to content


Photo

keep variable value


  • Please log in to reply
8 replies to this topic

#1 Bee

Bee
  • Members
  • PipPipPip
  • Advanced Member
  • 40 posts

Posted 14 March 2006 - 08:58 PM

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

#2 obsidian

obsidian
  • Staff Alumni
  • Advanced Member
  • 3,202 posts
  • LocationSeattle, WA

Posted 14 March 2006 - 09:19 PM

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:
<?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>

hope this helps...

btw, i'm moving this to a more suitable topic area
You can't win, you can't lose, you can't break even... you can't even get out of the game.

<?php
while (count($life->getQuestions()) > 0)
{   $life->study(); } ?>
  LINKS: PHP: Manual MySQL: Manual PostgreSQL: Manual (X)HTML: Validate It! CSS: A List Apart | IE bug fixes | Zen Garden | Validate It! JavaScript: Reference Cards RegEx: Everything RegEx

#3 Bee

Bee
  • Members
  • PipPipPip
  • Advanced Member
  • 40 posts

Posted 14 March 2006 - 10:37 PM

[!--quoteo(post=355055:date=Mar 14 2006, 04:19 PM:name=obsidian)--][div class=\'quotetop\']QUOTE(obsidian @ Mar 14 2006, 04:19 PM) View Post[/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:
<?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>

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

#4 keeB

keeB
  • Staff Alumni
  • Advanced Member
  • 1,078 posts
  • LocationCalifornia

Posted 14 March 2006 - 11:21 PM

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

Come visit my site to see my latest projects
http://nick.stinemates.org/wordpress/


#5 Bee

Bee
  • Members
  • PipPipPip
  • Advanced Member
  • 40 posts

Posted 14 March 2006 - 11:34 PM

[!--quoteo(post=355122:date=Mar 14 2006, 06:21 PM:name=keeB)--][div class=\'quotetop\']QUOTE(keeB @ Mar 14 2006, 06:21 PM) View Post[/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.

#6 keeB

keeB
  • Staff Alumni
  • Advanced Member
  • 1,078 posts
  • LocationCalifornia

Posted 15 March 2006 - 08:06 AM

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..
<?
//Session Example.
session_start();

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

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

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

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

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

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

GOOD LUCK!




Come visit my site to see my latest projects
http://nick.stinemates.org/wordpress/


#7 Bee

Bee
  • Members
  • PipPipPip
  • Advanced Member
  • 40 posts

Posted 15 March 2006 - 12:22 PM

[!--quoteo(post=355263:date=Mar 15 2006, 03:06 AM:name=keeB)--][div class=\'quotetop\']QUOTE(keeB @ Mar 15 2006, 03:06 AM) View Post[/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..
<?
//Session Example.
session_start();

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

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

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

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

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

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:
<?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")
?>

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

#8 Bee

Bee
  • Members
  • PipPipPip
  • Advanced Member
  • 40 posts

Posted 17 March 2006 - 12:19 AM

[!--quoteo(post=355048:date=Mar 14 2006, 03:58 PM:name=Bee)--][div class=\'quotetop\']QUOTE(Bee @ Mar 14 2006, 03:58 PM) View Post[/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!

#9 keeB

keeB
  • Staff Alumni
  • Advanced Member
  • 1,078 posts
  • LocationCalifornia

Posted 17 March 2006 - 04:42 AM

change..

$_SESSION['$category'] = $_POST['cat'];

to..

$_SESSION['category'] = $_POST['cat'];

silly man :D

Come visit my site to see my latest projects
http://nick.stinemates.org/wordpress/





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users