1

Building a plugin in one of my not to strong languages, PHP.

In this plugin i need a function that stores a ID for me and increase it with given value on every execution. With this code i could achieve: for every execution increase given value with +1

$wpdb->query("UPDATE `wp_selector` SET `name`= name+1  WHERE 1"); 

Result upon every execution: 1, 2, 3, 4, 5..etc

Did try to use same method where my initial value was something like 'ABC000001' trying to achieve ABC000001, ABC000002, ...ABC056211

Result: 1,2,3..

When Plugin activates i create table and put my initial value like 'ABC000001' in 'name'

How can i increase the value with +1 and keep the structure of my value, So it will go to 'ABC000001'and continue it increment so it finally would end up like 'ABC999999'and not 'ABC00000999999'

Mathias Asberg
  • 3,562
  • 6
  • 30
  • 46
  • possible duplicate of [How to make MySQL table primary key auto increment with some prefix](http://stackoverflow.com/questions/17893988/how-to-make-mysql-table-primary-key-auto-increment-with-some-prefix) – sunshinejr Feb 16 '15 at 15:20
  • I don't think so, That question is regarding creating new rows with increasing value and does not seem like the best solution for me. There must be a better solution.. there is always ! – Mathias Asberg Feb 16 '15 at 15:23

1 Answers1

1

Storing custom global data is what the wp_options table is for and Wordpress has some functions to help you with this. You could go a few different ways with this depending on exactly how you want it to work but I would do something like this...

function myplugin_create_id() {
    //Check if you have an ID stored
    $current_id = get_option( 'myplugin_id', 1 );

    //Add one to create new ID
    $new_id = $current_id + 1;

    //Update option in DB
    update_option( 'myplugin_id', $new_id );

    //Create string in correct format
    $formatted_id = 'ABC';
    $formatted_id .= str_pad( $current_id, 6, "0", STR_PAD_LEFT);

    //Return formatted ID
    return $formatted_id;
}

this function stores a number in the options table, adds 1 to the number every time and returns a formatted string by prepending the number stored with 'ABC' and using str_pad() to make sure the number string is 6 digits long.

Now everytime you want to generate a new ID you can just use...

$id = myplugin_create_id();

Hope that is the answer you're looking for.

Regards

Dan

danbahrami
  • 1,014
  • 1
  • 9
  • 14