自我提交表单和cookie PHP

时间:2014-04-23 00:44:27

标签: javascript php jquery cookies

我有一个从数据库获取信息的表单,在用户注册后将它们发送到他们从单选按钮中进行选择的页面,在每次选择后我想保存选择"总共10个&#34 ;第一次显示页面时,显示的第一个选项和之后没有任何内容。 $ count保持在1"不增加"有人可以查看我的代码并告诉我原因。

<?php       
if(isset($_COOKIE['counter'])){
    $count = isset($_COOKIE['counter']);
    print($count);
}
else{
    $count = 1;
    print("Shouldn't see this after first click");
}

$connection = mysqli_connect("localhost", "root", "", "worldcup2014db");
// Check connection
if (mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$querySelection = "SELECT * from teamselections where id = '$count'";

$resultSelection = mysqli_query($connection , $querySelection);

        print("<form method='post' action='selection.php'>");

        while($row = mysqli_fetch_array($resultSelection)){
            $t1 = $row['team1id'];
            $t2 = $row['team2id'];
            $t3 = $row['team3id'];
            $t4 = $row['team4id'];



                if($row['teamid'] == $t1){
                    $tName1 = $row['name'];
                }
                if($row['teamid'] == $t2){
                    $tName2 = $row['name'];
                }
                if($row['teamid'] == $t3){
                    $tName3 = $row['name'];
                }
                if($row['teamid'] == $t4){
                    $tName4 = $row['name'];
                }                   
            }

            print("<input type='radio' id='rd1' name='teamname' value='$t1'>$tName1</input>");
            print("<input type='radio' id='rd2' name='teamname' value='$t2'>$tName2</input>");
            if($count > 4){
                print("<input type='radio' id='rd3' name='teamname' value='$t3'>$tName3</input>");
                print("<input type='radio' id='rd4' name='teamname' value='$t4'>$tName4</input>");  
            }

            print("<input type=\"submit\" name=\"submit\" value=\"Continue\">");                            
        }
        $count++; // increment count
        print("</form>");

        setcookie('counter', $count);
        print($count);

        mysqli_close($connection);          

&GT;

screenshot of when page loads first

screenshot after continue is clicked, count set back to 1

screenshot of cookie setting in browser

提前致谢

GMAN

1 个答案:

答案 0 :(得分:1)

您的$count++;超出while($row = mysqli_fetch_array($resultSelection)){循环

像这样:

        print("<input type=\"submit\" name=\"submit\" value=\"Continue\">");  
        $count++; // increment count                          
    }
    print("</form>");

正如@Devon所述,第三行应为:

$count = $_COOKIE['counter'];