【问题标题】:MySQL: Undefined indexes, even though they have been definedMySQL:未定义的索引,即使它们已被定义
【发布时间】:2011-10-25 21:03:51
【问题描述】:

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

$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”,那么为什么它说它还没有定义呢?

【问题讨论】:

  • 很抱歉,如果描述似乎稀疏,我只是不知道如何描述它

标签: php mysql indexing


【解决方案1】:

要将结果行作为关联数组获取,您应该使用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 

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      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++;
      }
      

      【讨论】:

        【解决方案4】:

        只需尝试 mysql_fetch_assoc。

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-08-27
            • 2022-01-21
            • 2012-09-03
            • 2019-04-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-25
            相关资源
            最近更新 更多