注意:未定义的偏移量:0 in

2022-08-30 08:27:21

我收到这个PHP错误,这是什么意思?

Notice: Undefined offset: 0 in 
C:\xampp\htdocs\mywebsite\reddit_vote_tut\src\votes.php on line 41

从此代码中:

<?php 
include("config.php"); 

function getAllVotes($id) 
{ 
    $votes = array(); 
    $q = "SELECT * FROM entries WHERE id = $id"; 
    $r = mysql_query($q); 
    if(mysql_num_rows($r)==1)//id found in the table 
    { 
        $row = mysql_fetch_assoc($r); 
        $votes[0] = $row['votes_up']; 
        $votes[1] = $row['votes_down']; 
    } 
    return $votes; 
} 

function getEffectiveVotes($id) 
{ 
        $votes = getAllVotes($id); 
        $effectiveVote = $votes[0] - $votes[1];    //ERROR THROWN HERE
        return $effectiveVote; 
} 

$id = $_POST['id']; 
$action = $_POST['action']; 

//get the current votes 
$cur_votes = getAllVotes($id); 

//ok, now update the votes 

if($action=='vote_up') //voting up 
{ 

    $votes_up = $cur_votes[0]+1;     //AND ERROR THROWN HERE


    $q = "UPDATE threads SET votes_up = $votes_up WHERE id = $id"; 
} 
elseif($action=='vote_down')
{ 
    $votes_down = $cur_votes[1]+1; 
    $q = "UPDATE threads SET votes_down = $votes_down WHERE id = $id"; 
} 

$r = mysql_query($q); 
if($r)
{ 
    $effectiveVote = getEffectiveVotes($id); 
    echo $effectiveVote." votes"; 
} 
elseif(!$r) //voting failed 
{ 
    echo "Failed!"; 
} 
?>

答案 1

您正在要求 在 键 处的值。它是一个不包含该键的数组。0$votes

数组未设置,因此当 PHP 尝试访问数组的键时,它会遇到 [0] 和 [1] 的未定义偏移量并引发错误。$votes0

如果你有一个数组:

$votes = array('1','2','3');

我们现在可以访问:

$votes[0];
$votes[1];
$votes[2];

如果我们尝试访问:

$votes[3];

我们将收到错误“注意:未定义的偏移量:3”


答案 2

首先,检查数组是否确实存在,您可以尝试类似

if (isset($votes)) {
   // Do bad things to the votes array
}

推荐