2

I was searching for hours now and still couldn't find the correct answer. This might seem simple but I need your help, here's the Problem: There are two buttons, 1.) increment button and 2.) decrement(subtract) button, when I click button 1, the value $a get +1 when I click button 2, $a get -1.

Seems simple right?

It should go back to the same page (reload), with the changed value $a

ex: $a = 0;
1.) click increment button 2.) reload page $a = 1; 3.) click decrement button $a=0

very simple, I'm just not that good to figure it out on my own.

4

2 回答 2

0

如果要在重新加载/页面更改后保存要使用的变量,则需要将该变量存储在 cookie 或会话中。在这种情况下,我会推荐会话。所以这里有一个例子:

脚本名称: index.php

<?PHP
    /* You need to start a session in order to 
    *  store an retrieve variables. 
    */
    session_start();
    if(!isset($_SESSION['value'])) { // If no session var exists, we create it.
        $_SESSION['value'] = 0; // In this case, the session value start on 0.
    }

    if(isset($_GET['action'])) {
        switch($_GET['action']) {
            case 'add': // Yeah, PHP allows Strings on switchs.
                $_SESSION['value'] ++;
            break;
            case 'remove':
                $_SESSION['value'] --;
            break;
        }
        /* If you avoid the next two lines, you'll be adding or removing when
        *  you refresh, so we'll redirect the user to this same page.
        *  You should change the 'index.php' for the name of your php file.
        */
        header("Location: index.php");
        exit();
    }
?>

<html>
    <head>
        <title>:: Storing user values in session ::</title>
    </head>
    <body>
        <p>The current value is: <?PHP echo $_SESSION['value']; ?></p>
        <p><a href="?action=add" target="_SELF">Increase value</a></p>
        <p><a href="?action=remove" target="_SELF">Decrease value</a></p>
    </body>
</html>

如果您将该代码保存在一个名为“index.php”的单个 php 文件中,您将看到您正在寻找的行为。

我希望这对您有所帮助,并祝您新年快乐!

PS:请注意,在这种情况下,我只使用单一的动作。我在这里没有使用 Javascript,因为您的问题的标题是 PHP。如果您想使用 Javascript 或 JQuery 执行此操作,请告诉我。

于 2012-12-27T17:36:22.650 回答
0

我不是 php 开发人员,但根据您的问题,我了解到您丢失了变量的值,因为它重新加载并将所有变量重置为默认值。您确定要做的是持久化(可能在 cookie、会话或服务器中,并始终从这些存储中加载值)。

于 2012-12-27T17:34:06.400 回答