yosafat
yosafat

Reputation: 253

php yii2 how to make automaticly id in query yii2 insert?

i have a code like this ,

        $request = Yii::$app->request;
        $post = $request->post();

        $filesettingid = $post['filesettingid'];
        $checkboxValue = $post['selection'];


        for($i=0;$i<sizeof($checkboxValue);$i++) {
            $store = Yii::$app->db->createCommand('SELECT id FROM store WHERE port='.$checkboxValue[$i])->queryAll(); 
            $storeid = $store[$i]['id'];

            Yii::$app->db->createCommand()->insert('tes', 
                            [
                                'id' => $i+1,
                                'filesetting_id' => $filesettingid,
                                'store_id' => $storeid  
                            ])->execute();
        }

what i want is, each i insert the new data, id will generate automaticly like 1,2,3,4.

the problem in above code is, the ID always be 1.

is it possible to make it real? so what i want is :

First time insert, id = 1, second is id = 2 , and that is happen automatically.

Upvotes: 0

Views: 1304

Answers (1)

Dmitri Sandler
Dmitri Sandler

Reputation: 1172

Have you considered setting database engine to auto increment values with each insert?

Take as an example Yii2 default user table. ID filed is auto incremented, and you don't have to worry about setting it problematically. Every time you send a new insert engine increments ID filed by itself. See default migration under "advanced template"\console\migrations\m130524_201442_int. (your file name might be different depending on the Yii2 version)

$this->createTable('{{%user}}', [
    'id' => $this->primaryKey(),
    'username' => $this->string()->notNull()->unique(),
    'auth_key' => $this->string(32)->notNull(),
    'password_hash' => $this->string()->notNull(),
    'password_reset_token' => $this->string()->unique(),
    'email' => $this->string()->notNull()->unique(),

    'status' => $this->smallInteger()->notNull()->defaultValue(0),
    .........
], $tableOptions);

When setting 'id' to primary key database automatically knows to auto increment it. If you already have a table the ID field is not primary key you can use the followign migration:

$this->alterColumn('{{%databaseName}}', 'columnName', $this->integer()->notNull().' AUTO_INCREMENT');

You can also set it from management console, or run a SQL query. Depending on database engine you are using this might look a little different but the concept is the same.

MYSQL:

In MySQL workbench right click on table in question, select Alter Table and check NNm and AI next to column you want auto increment. See Screenshot

Or run command:

ALTER TABLE `dbName`.`nameOfTheTable` MODIFY `columnName` INT AUTO_INCREMENT NOT NULL;

I am a bit rusty on my SQL, so if it does not work let me know I will get you right command.

Hope this helps. Good luck.

Upvotes: 1

Related Questions