【发布时间】:2011-09-26 19:59:29
【问题描述】:
我收到这个 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!";
}
?>
【问题讨论】:
-
你的代码很危险!它可以用于sql注入!
-
@Bernd Ott 那么我该如何排序呢?
-
使用允许查询参数的数据库层和/或使用 mysql_real_escape_string 参见php.net/manual/de/function.mysql-real-escape-string.php 还有一些不错的示例。
-
我想指出,mysqli_real_escape_string 仍然容易受到 SQL 注入的影响,在撰写本文时(2020 年)应该不鼓励这样做。准备好的语句是现在要走的路。