tags:

views:

58

answers:

5
$query = "SELECT COUNT(t.id), SUM(t.num_replies) FROM threads AS t WHERE t.forum_id=$forum_id";

$result = mysql_query($query);
list($num_threads, $num_posts) = mysql_fetch_assoc($result);

Equals:

Notice: Undefined offset: 1 in C:\wamp\www\includes\functions.php on line 11

Notice: Undefined offset: 0 in C:\wamp\www\includes\functions.php on line 11

Any ideas how i can get rid of these notices?

+2  A: 

list() only works on enumerated arrays. The mysql_fetch_assoc() function returns an associative one. Use mysql_fetch_row() instead.

Daniel Egeberg
+3  A: 

http://php.net/mysql_fetch_assoc

array mysql_fetch_assoc ( resource $result )

Returns an associative array...

http://php.net/manual/en/function.list.php

array list ( mixed $varname [, mixed $... ] )

Note: list() only works on numerical arrays and assumes the numerical indices start at 0.

You can't assign to variables via list from an associative array. Either use mysql_fetch_row or, usually better, just use $row = mysql_fetch_assoc($result) and work with $row as an array. You don't really want to use _fetch_row, since then the sanity of your application hinges on the order the parameters are in in your query, which is something that can break all too easily.

deceze
A: 

The list() function does only work with numeric array, so you have to use mysql_fetch_row() instead:

list($num_threads, $num_posts) = mysql_fetch_row($result);
Kau-Boy
A: 

As mentioned already, you don't need to use mysql_fetch_assoc because it will return both numerical and string indeces.. So for two values you'll get four. Which is why you have an undefined offset. You ask to list() two variables from an array that has four values

$result = mysql_query($query);
list($num_threads, $num_posts) = mysql_fetch_array($result, MYSQL_NUM);

By using mysql_fetch_array you can specify that you only want the numerical indeces by appending the parameter; MYSQL_NUM

Zane Edward Dockery
mysql_fetch_assoc() will return only an associative array, mysql_fetch_row() only a numeric and mysql_fetch_array() will return both. That's why you can use the MYSQL_NUM flag on that function. But if you only want numbers, you should take the mysql_fetch_row() function.
Kau-Boy
I just now realized my error there. I need sleep :)
Zane Edward Dockery
+1  A: 

This code could error further if you have a syntatical error or theres a problem with mysql_query. If mysql_query does not return a valid result then passing that into mysql_fetch_assoc or mysql_fetch_numeric will cause an error.

I recommend that you validate the return value of mysql_query and mysql_fetch_* before trying to use information from it's return value.

$result = mysql_query($query) or die('query error: ' . mysql_error());
$num_threads = $num_posts = 0;
if($result !== false && ($row = mysql_fetch_row($result)) !== false) {

     $num_threads = $row[0];
     $num_posts   = $row[1];
}
Paul Dragoonis