-1

I want to write a function in appModel that returns next auto increment primary id for each model I want. For example in UserController I use $this->user->nextId(). I know the query that returns next auto increment primary id:

SELECT Auto_increment FROM information_schema.tables WHERE table_name='table-name' AND table_schema='db-name'
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
  • 9
    why do you want this? such code is not reliable. consider two users on your site at the same one. both retrieve the auto_inc at the same time, get (say) 42, and both use it. One will lose with a primary key violation. It's a race, and someone WILL lose. – Marc B Nov 26 '13 at 13:56
  • You should learn how to use the framework properly. Then you will discover that you never ever even need that functionality. Besides what Marc B mentioned: that it doesnt make sense to use it. – mark Nov 26 '13 at 14:14
  • yes you are right,but I need it. – beautifulmind Nov 26 '13 at 14:16
  • user model was just an example.most of time one user need next id. – beautifulmind Nov 26 '13 at 14:18
  • I don't understand. You seem to answer your question yourself: "I want to write a function in appModel that returns next auto increment primary id". "I know the query that returns next auto increment primary id". – Boann Nov 26 '13 at 14:21
  • I dont know how to write custom query in cakephp – beautifulmind Nov 26 '13 at 14:22
  • duplicate of http://stackoverflow.com/questions/21373063/using-cakephp-to-insert-rows-into-a-table-with-one-identity-column-only – flowtron Jun 29 '16 at 17:32

1 Answers1

0

http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query

So you could do this:

public function nextId() {
    $result = $this->User->query("SELECT Auto_increment FROM information_schema.tables AS NextId  WHERE table_name='table-name' AND table_schema='db-name'");
    return $result[0]['NextId']['Auto_increment'];
}

You may need to edit the return statement. I am not sure if that is the exact format it will use.

As others have said, though, this isn't something you should be doing.

iso27002
  • 179
  • 7
  • Two vistors calling this at the same time will mean one of them will get an ID error! Use this: http://stackoverflow.com/a/38106365/3022387 – flowtron Jun 29 '16 at 17:28