Getting Last Inserted Id From MySQL in Yii

2019-02-11 11:25发布

I want to show the last login id from the database in view > _form.php file.I have made the code in _form.php file like this

  <div class="row">
    <?php echo $form->labelEx($model,'id'); ?>
    <?php echo Yii::app()->db->getLastInsertId('Form');?>
    <?php echo $form->error($model,'id'); ?>
  </div>

Here Form is the table and the model name.But Still I am getting ID:0.Where is the wrong part?

标签: php mysql yii
3条回答
小情绪 Triste *
2楼-- · 2019-02-11 11:45
$max = Yii::app()->db->createCommand()->select('max(id) as max')->from('TABLENAME')->queryScalar();

Just add one to get the next.

查看更多
仙女界的扛把子
3楼-- · 2019-02-11 11:50

Pekka's answer is good for common. But if you want to do that action in Yii Framework, try this:

$myModel = new $model;
$model -> savel(false);
echo $model->primaryKey; // Prints the last id.

Or you may try this too for general solution:

Yii::app()->db->getLastInsertID();

Finally, I suggest you to check out this

查看更多
4楼-- · 2019-02-11 12:01

All the last_insert_id functions (be they PHP wrappers or the native mySQL one) typically refer to the last ID created using the current database connection. The last login was probably not created during the same request you are showing the table in, so this method won't work for you.

Use a normal SELECT to find out the newest login instead - e.g. by using ORDER by creationtime DESC LIMIT 1.

Related: How to get a highest field value in a table in MySQL?

查看更多
登录 后发表回答