Average Joe
Average Joe

Reputation: 4601

PHP list issue ( Undefined offset: )

Original SQL query is this; SELECT id,post_title,post_date FROM wp_posts where id='1'

When I retrieve the record, I am finding it but when it comes to returning the results, I am puzzled. Here is the where I got stuck.

   while ($row = mysql_fetch_assoc($RS)) :
      print_r ($row); 
      list($id,$post_title,$post_date) = $row;
   endwhile;

print_r ($row) outputs this; Array ( [ID] => 1 [post_title] => Hello world! [post_date] => 2012-03-27 03:28:27 )

And when I run the list function in there ( for debug purposes obviously ), I get this;

Notice: Undefined offset: 2 in F:\inetpub\wwwroot\whatever\sql.php on line 147
Notice: Undefined offset: 1 in F:\inetpub\wwwroot\whatever\sql.php on line 147
Notice: Undefined offset: 0 in F:\inetpub\wwwroot\whatever\sql.php on line 147

What's causing this?

Upvotes: 7

Views: 9390

Answers (5)

Ravi
Ravi

Reputation: 17

$categ = val1 | val2

list($one,$two,$three)=@split('[|]',$categ);

If you try to list the value which is not available it will return the error Undefined Offset.

Here the error will be Undefined Offset 2.

Because while spliting $categ, it will have only two values, if you try to access third value then it will return error.

Upvotes: 0

summea
summea

Reputation: 7593

You might be able to use extract() here instead, as well; (documentation here.)

Upvotes: 2

stewe
stewe

Reputation: 42642

Replace:

mysql_fetch_assoc($RS)

with:

mysql_fetch_array($RS, MYSQL_NUM)

then it should work, because the list function trys to access the array using numeric keys.

Upvotes: 6

webjprgm
webjprgm

Reputation: 4581

You used mysql_fetch_assoc, so the resulting array per row has data under a key by column name, whereas "list" tries to match variables to values using numerical array indexes. You can use mysql_fetch_array instead.

Upvotes: 1

Average Joe
Average Joe

Reputation: 4601

I guess the answer lies somewhere within this;

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

:(

Upvotes: 6

Related Questions