Jump to content

Autoincrement a certain field of a certain template


owzim
 Share

Recommended Posts

Is there a neat an straightforward PW way of incrementing a value of a field other than getting all pages with that template an figuring out the highest value through a loop or something? 

In this case it should not be a regular auto increment but a number one higher than the highest of the already inserted pages.

  • Like 1
Link to comment
Share on other sites

Greetings,

Interesting coincidence... I was just this morning trying to figure out a neat way to do this. In my case, I am building a site with property listings, and I want to auto-generate the listing numbers.

I was thinking of just tying into the page ID.

Would be interested in other ideas...

Thanks,

Matthew

Link to comment
Share on other sites

Sometimes I setup a table for counters...

 CREATE TABLE counters (
   count int(10) unsigned NOT NULL DEFAULT '0' ,
   name char(10) NOT NULL ,
   PRIMARY KEY (name)
 );

And a function like this:

function bumpCount($mysqli, $name){
    if($result = $mysqli->query("UPDATE counters SET count = LAST_INSERT_ID(count+1) WHERE name = \"$name\"")){
        $count = $mysqli->insert_id;
        if($count>0) return $count;    //normal
        if($result = $mysqli->query("INSERT INTO counters (count, name) VALUES (1, \"$name\")")) return 1;    //initialize new counter
    }
    return false;
}

And use it like this:


$mysqli = new mysqli('host', 'user', 'password', 'database');
echo 'The counter is: ' . bumpCount($mysqli, 'foo');

If anything goes wrong it returns false.

New counters are setup automatically when you use a new name. First number issued is 1.

The usual disclaimers about code examples apply.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...