Pear DB and “DB Error: already exists” On Insert

Note that this post relates to using a MySQL database in conjunction with the PEAR DB module, or any other PEAR module that depends on DB – like DB_TABLE (which I’ve been enjoying).

You might run into this error if you switch over from using PHP’s built-in MySQL functions, over to a database abstraction layer, which is what I did on a recent project. After much banging-the-head-on-the-desk, I finally figured out that PEAR DB doesn’t use the same auto-increment sequence that the actual MySQL engine does.

For example, you may have a database using a CMS that doesn’t use PEAR. You do your various inserts, and inevitably, your deletes. So, your auto-increment column might start out in a perfect sequence like 1 – 2 – 3 – 4 – 5, etc. But then say the first two get deleted, so now your sequence id’s are 3 – 4 – 5. But then you insert again, and your CMS, using the DBMS directly, knows to use 6 for the next auto-increment value.

But then say you switch over to PEAR DB, and why wouldn’t you? It’s great – and readily bundled into most PHP installations. But then you notice, taking the above example, that your next insert starts at 1. Then the next insert produces an id of 2. And then you get to 3 and WHOA what happens, “DB Error: already exists” that’s wtf happens. PEAR DB ignores MySQL’s auto-increment sequence and makes its own (jump down to the notes/warnings in red).

You may also notice that you have table names with “_seq” at the end.

Why is this? I have no idea – but it’s stooooopid. Is there some reason for this? Seriously, please enlighten me! I mean, what’s an example of where you’d like to use more than 1 sequence?

seqSo what to do? You need to alter those “_seq” tables, that’s what. So if you’re having trouble inserting into a table named “products” – get MySQL’s “Next Autoindex” value, which you can easily do in phpMyAdmin on a table’s “structure” tab (see the screenshot, where it’s 20).

Now, go into the products_seq table, and change the id to that number (20 in this case). Now you shouldn’t have any problems.

So the moral of the story is, if you start out using a PEAR database abstraction layer, you’ll never have this problem. But if you’re unlucky enough to not have done that in the first place and switch over to it, you may have this issue and this is a quick fix.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>