简体   繁体   中英

Increase DB value containing Text + Numbers with +1 | Wordpress

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. W ith 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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM