MySQL:未定义的索引,即使它们已被定义


MySQL: Undefined indexes, even though they have been defined

我有一些非常简单的代码:

$result = mysql_query("
SELECT  max(id) as id, ip, max(entry), COUNT(ip) AS count 
FROM table_name
GROUP BY ip
ORDER BY max(id) asc
");
$i = 0;
$num_rows = mysql_num_rows($result);
echo $num_rows;

while($row = mysql_fetch_row($result)) {
    $id = $row['id'];
    $entry = $row['entry'];
    $ip = $row['ip'];
    $count = $row['count'];
    $i++;
?>

<tr width="100%" align="center">
    <td><?php echo $i; ?></td>
    <td><?php echo $id; ?></td>
    <td><?php echo $entry; ?></td>
    <td><?php echo $ip; ?></td>
    <td><?php echo $count; ?></td>
    <td>
    <form style="display:inline;" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <input type="hidden" value="<?php echo $ip; ?>" name="ip" />
        <input type="hidden" value="<?php echo $id; ?>" name="id" />
        <input type="submit" value="Ban IP" name="submit" />
    </form>
    </td>
</tr>
<?php
}

问题是当我运行它时,我得到:

Notice: Undefined index: id
Notice: Undefined index: entry
Notice: Undefined index: ip
Notice: Undefined index: count

但据我所知,我已经在 SQL 语句中定义了索引,任何帮助将不胜感激。它使用列名 id、ip、entry 选择数据,并为 ip 的计数创建索引"count",那么为什么它说它还没有被定义呢?

要将结果行作为关联数组获取,您应该使用 mysql_fetch_assoc 而不是 mysql_fetch_row

此外,尽管您声称自己有,但您还没有定义entry。更改此设置:

SELECT max(id) as id, ip, max(entry), COUNT(ip) AS count 

对此:

SELECT max(id) as id, ip, max(entry) AS entry, COUNT(ip) AS count 

您正在使用 mysql_fetch_row() ,它将数据作为索引数组返回。你想要mysql_fetch_assoc()

mysql_fetch_row返回一个枚举数组。

你想要mysql_fetch_array.

或者,您可以按列索引获取值:

while($row = mysql_fetch_row($result)) {
    $id = $row[0];
    $ip = $row[1];
    $entry = $row[2];
    $count = $row[3];
    $i++;
}

试试mysql_fetch_assoc。

你需要mysql_fetch_assocmysql_fetch_row返回一个带有数字索引的普通数组。