AviateX14
AviateX14

Reputation: 760

MySQL: Undefined indexes, even though they have been defined

I have some pretty simple code:

$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
}

The problem is that when I run it, I get:

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

But as far as I can see, I have defined the indexes in the SQL statement, any help would be appreciated. It selects the data using the column names id, ip, entry and creates the index "count" for the count of ip's, so why does it say that it hasn't been defined?

Upvotes: 3

Views: 5348

Answers (5)

Karoly Horvath
Karoly Horvath

Reputation: 96366

You need mysql_fetch_assoc, mysql_fetch_row returns a plain array with numerical indexes.

Upvotes: 0

Tobias Golbs
Tobias Golbs

Reputation: 4616

Just try mysql_fetch_assoc instead.

Upvotes: 0

Farray
Farray

Reputation: 8548

mysql_fetch_row returns an enumerated array.

You want mysql_fetch_array.

Alternatively you could fetch values by column index:

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

Upvotes: 0

Marc B
Marc B

Reputation: 360922

You're using mysql_fetch_row(), which returns the data as an indexed array. You want mysql_fetch_assoc() instead.

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 839254

To get the result row as an associative array you should use mysql_fetch_assoc instead of mysql_fetch_row.

Also you haven't defined entrydespite your claim that you have. Change this:

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

To this:

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

Upvotes: 4

Related Questions