如何使用请求POST从数据库(MySQL)中删除记录?
在视图中:
<a href="<?= Url::to(['user/delete', 'id' => Html::encode($user->id)]) ?>" class="btn btn-danger">Delete</a>
在控制器中:
public function actionDelete($id)
{
$model = User::findOne($id);
if (Yii::$app->request->isPost) {
$model->delete();
Yii::$app->session->setFlash('success', 'User deleted successfully');
}
return $this->redirect(['user/index']);
}
此代码仅在请求GET时删除。
像这样设置删除按钮
<?= Html::a('Delete', ['user/delete', 'id' => $user->id], [
'class' => 'btn btn-danger',
'data-confirm' => 'Are you sure?',
'data-method' => 'post',
]) ?>
和Html类是
使用yii \ helpers \ Html;