3

I need to retrieve the ID of the AUTO_INCREMENT value of the last query.

My query looks like this:

  $result = $wpdb->query( $wpdb->prepare( "
    INSERT INTO $table_name
    ( name, season, copyright, description, path )
    VALUES ( %s, %s, %s, %s, %s )", 
    $galleryData['name'], $galleryData['season'], $galleryData['copyright'], $galleryData['description'], $galleryData['path'] ) );

  // Let's output the last autogenerated ID.
  echo $wpdb->insert_id;

  // This returns the same result
  echo mysql_insert_id();

Looking at my DB table, I see rows counting from 1 to 24 (24 rows). But using $wpdb->insert_id or mysql_insert_id() returns 241.

Doing new inserts will return 251, 261, 271 and so on. Why do I et the extra '1' at the end?

UPDATE
Thanks to Pekka (I'd better stad running a tab on the number of beers I owe him), I figured it out.

Further down the code I got this:

  if(!$result)
    _e("[DB error] Ups. Something went wrong when trying to insert the event.");
  else
    echo true;

It's the last statement (echo true) that is outputed!

5
  • You're saying that the code above echoes 241241, 251251, etc.? Oct 18, 2010 at 23:39
  • 1
    I'll bet a beer there is something somewhere that outputs a boolean variable (which translates to 1 when echoed).
    – Pekka
    Oct 18, 2010 at 23:41
  • No, running EITHER $wpdb->insert_id OR mysql_insert_id() will return 241, 251, 261 and so on. The first to numbers are correct, but then the 1 is added. Looking in MySQL, the highest ID is 26.
    – Steven
    Oct 18, 2010 at 23:42
  • So then what does the code above result in? Oct 18, 2010 at 23:43
  • 1
    can you try echo "'".mysql_insert_id()."'";? If this outputs '241' with the 1 wrapped inside the quotes, I'll believe it, but not before ;)
    – Pekka
    Oct 18, 2010 at 23:44

1 Answer 1

15

I am betting a delicious Kölsch:

alt text

that the reason actually is an echo later in the code, that echoes some boolean variable, whose true will translate to 1.

If I am wrong, I shall take the downvotes like a man.

(Forgive the silly answer, it's very late already and I'm still working :)

Update: Ahh, joy, I was right!

2
  • 1
    Ach ja. Du bist voll korrekt! Next time I go to Germany, I'll buy you a large cold Kölsch ;) Although I am surprised you live in Germany. Pekka sounds very Finish :) And yes, I'm working late too!
    – Steven
    Oct 19, 2010 at 0:10
  • 1
    @Steven hey, always welcome! :) I'm half finnish, hence the name. I'm calling it a day soon, `night!
    – Pekka
    Oct 19, 2010 at 0:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.