0

为什么我在尝试轮询时在 ajax 中看到此错误消息“(!)注意:未定义的索引:第 6 行的 D:\wamp\www\poll\poll.php 中的轮询”.. 我有两个文件

1- index.html 包含获取请求

2- poll.php 文件选择请求并显示结果

索引.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"  dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>AJAX Poll Using jQuery and PHP</title>

<link rel="stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript" src="js/jquery-1.3.2.js" ></script>
<script type="text/javascript" >
$(function(){
    var loader=$('#loader');
    var pollcontainer=$('#pollcontainer');
    loader.fadeIn();
    //Load the poll form
    $.get('poll.php', '', function(data, status){
        pollcontainer.html(data);
        animateResults(pollcontainer);
        pollcontainer.find('#viewresult').click(function(){
            //if user wants to see result
            loader.fadeIn();
            $.get('poll.php', 'result=1', function(data,status){
                pollcontainer.fadeOut(1000, function(){
                    $(this).html(data);
                    animateResults(this);
                });
                loader.fadeOut();
            });
            //prevent default behavior
            return false;
        }).end()
        .find('#pollform').submit(function(){
            var selected_val=$(this).find('input[name=poll]:checked').val();
            if(selected_val!=''){
                //post data only if a value is selected
                loader.fadeIn();
                $.post('poll.php', $(this).serialize(), function(data, status){
                    $('#formcontainer').fadeOut(100, function(){
                        $(this).html(data);
                        animateResults(this);
                        loader.fadeOut();
                    });
                });
            }
            //prevent form default behavior
            return false;
        });
        loader.fadeOut();
    });

    function animateResults(data){
        $(data).find('.bar').hide().end().fadeIn('slow', function(){
                            $(this).find('.bar').each(function(){
                                var bar_width=$(this).css('width');
                                $(this).css('width', '0').animate({ width: bar_width }, 1000);
                            });
                        });
    }

});
</script>
</head>
<body>
    <div id="container" >
        <h1>User Poll</h1>
        <div id="pollcontainer" >
        </div>
        <p id="loader" >Loading...</p>
    </div>
</body>
</html>

投票.php

  <?php
    //Update database information according to your server settings
    $conn=mysql_connect('localhost', 'root', '') or die("Can't connect to mysql host");
    //Select the database to use
    mysql_select_db('ahmed') or die("Can't connect to DB");
    if(!$_POST['poll'] || !$_POST['pollid']){
        $query=mysql_query("SELECT id, ques FROM questions ORDER BY id DESC LIMIT 1");
        while($row=mysql_fetch_assoc($query)){
            //display question
            echo "<p class=\"pollques\" >".$row['ques']."</p>";
            $poll_id=$row['id'];
        }
        if($_GET["result"]==1 || $_COOKIE["voted".$poll_id]=='yes'){
            //if already voted or asked for result
            showresults($poll_id);
            exit;
        }
        else{
        //display options with radio buttons
            $query=mysql_query("SELECT id, value FROM options WHERE ques_id=$poll_id");
            if(mysql_num_rows($query)){
                echo '<div id="formcontainer" ><form method="post" id="pollform" action="'.$_SERVER['PHP_SELF'].'" >';
                echo '<input type="hidden" name="pollid" value="'.$poll_id.'" />';
                while($row=mysql_fetch_assoc($query)){
                    echo '<p><input type="radio" name="poll" value="'.$row['id'].'" id="option-'.$row['id'].'" /> 
                    <label for="option-'.$row['id'].'" >'.$row['value'].'</label></p>';
                }
                echo '<p><input type="submit"  value="Submit" /></p></form>';
                echo '<p><a href="'.$_SERVER['PHP_SELF'].'?result=1" id="viewresult">View result</a></p></div>';
            }
        }
    }
    else{
        if($_COOKIE["voted".$_POST['pollid']]!='yes'){

            //Check if selected option value is there in database?
            $query=mysql_query("SELECT * FROM options WHERE id='".intval($_POST["poll"])."'");
            if(mysql_num_rows($query)){
                $query="INSERT INTO votes(option_id, voted_on, ip) VALUES('".$_POST["poll"]."', '".date('Y-m-d H:i:s')."', '".$_SERVER['REMOTE_ADDR']."')";
                if(mysql_query($query))
                {
                    //Vote added to database
                    setcookie("voted".$_POST['pollid'], 'yes', time()+86400*300);               
                }
                else
                    echo "There was some error processing the query: ".mysql_error();
            }
        }
        showresults(intval($_POST['pollid']));
    }
    function showresults($poll_id){
        global $conn;
        $query=mysql_query("SELECT COUNT(*) as totalvotes FROM votes WHERE option_id IN(SELECT id FROM options WHERE ques_id='$poll_id')");
        while($row=mysql_fetch_assoc($query))
            $total=$row['totalvotes'];
        $query=mysql_query("SELECT options.id, options.value, COUNT(*) as votes FROM votes, options WHERE votes.option_id=options.id AND votes.option_id IN(SELECT id FROM options WHERE ques_id='$poll_id') GROUP BY votes.option_id");
        while($row=mysql_fetch_assoc($query)){
            $percent=round(($row['votes']*100)/$total);
            echo '<div class="option" ><p>'.$row['value'].' (<em>'.$percent.'%, '.$row['votes'].' votes</em>)</p>';
            echo '<div class="bar ';
            if($_POST['poll']==$row['id']) echo ' yourvote';
            echo '" style="width: '.$percent.'%; " ></div></div>';
        }
        echo '<p>Total Votes: '.$total.'</p>';
    }
4

3 回答 3

1

更改第 6 行poll.php

if(!$_POST['poll'] || !$_POST['pollid']){

到:

if(!isset($_POST['poll']) || !isset($_POST['pollid'])){


如所写,它假定存在$_POST['poll']并且 以它的值为null,false或为条件0。在值根本不存在的情况下,您看到的错误就是结果。解决方案是确认变量是否已使用isset().


另外,将第 15 行从:

if($_GET["result"]==1 || $_COOKIE["voted".$poll_id]=='yes'){

if((isset($_GET["result"]) && $_GET["result"] == 1) || (isset($_COOKIE["voted"  .$poll_id]) && $_COOKIE["voted" . $poll_id] == 'yes')){


类似地,正如所写,它假定存在$_GET['result']并且以它的价值为条件1。在值根本不存在的情况下,您看到的错误就是结果。解决方案再次是首先确认变量已经被设置,isset()然后检查它的值。



见: http: //php.net/manual/en/function.isset.php

于 2012-10-15T12:02:56.680 回答
0

你应该改变:

if(!$_POST['poll'] || !$_POST['pollid']){

if(!isset($_POST['poll']) || !isset($_POST['pollid'])){
于 2012-10-15T12:02:31.053 回答
0

当您的页面向 poll.php 发送一个没有请求数据的 GET 请求时,它会到达第 6 行并尝试评估 $_POST['poll']。除非此时 $_POST 数组中没有“poll”键,因此您会收到该错误。在尝试评估它们之前,使用 isset() 来测试数组键是否存在。如果你想测试一个键的存在并且它被设置为评估为 的东西true,那么你可以写:

if(isset($_POST['poll']) && $_POST['poll']){
    /*...code...*/
}

在之后评估 $_POST['poll'] 是可以的,&&因为如果 isset() 返回 false,它将停止评估。

另外,我注意到,至少在一种情况下,您将 $_POST 数据直接放入 mysql 查询中。不要那样做

这种处理太常见了,我用一个支持功能让它无忧;它做了三件事:1)null如果键不存在,则返回没有通知/错误 2)如果值确实存在,则转义字符串以防止 SQL 注入 3)进行一些可选的类型转换,这对于布尔值等非常有用。然后我可以用这种模式写:

$poll_id = $Input->get('poll_id', Input::INT);

if($poll_id) { /* do stuff */ }
于 2012-10-15T12:29:58.937 回答