在 Yii 中从 MySQL 获取最后插入的 ID

2022-01-04 00:00:00 php mysql yii

我想在视图中显示数据库中的最后一个登录ID > _form.php 文件.我在 _form.php 文件中制作了这样的代码

 

<?php echo $form->labelEx($model,'id');?><?php echo Yii::app()->db->getLastInsertId('Form');?><?php echo $form->error($model,'id');?>

这里的表格是表格和型号名称.但我仍然得到 ID:0.哪里出错了?

解决方案

Pekka 的回答对普通有好处.但是如果你想在 Yii Framework 中做那个动作,试试这个:

$myModel = 新的 $model;$模型 ->保存(假);echo $model->primaryKey;//打印最后一个 id.

或者你也可以试试这个作为通用解决方案:

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

最后,我建议您查看这个

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?

解决方案

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

相关文章