个性化阅读
专注于IT技术分析

YII数据库:创建(插入)记录示例

要将记录插入数据库中, 请执行以下步骤。我们已将Yii2文件夹命名为create。

步骤1创建模型文件

在frontend / models文件夹中创建一个模型文件child.php。

<?php namespace app\models; use Yii; class Child extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'child'; } /** * @inheritdoc */ public function rules() { return [ [['name', 'meaning', 'gender'], 'required'], [['name', 'meaning'], 'string', 'max' => 100], [['gender'], 'string', 'max' => 15] ]; } }

看上面的代码,

  • \ yii \ db \ ActiveRecord用于创建模型文件。
  • 在函数tableName中, 输入你正在使用的表名。
  • 函数规则定义表的输入。

步骤2建立控制器档案

在frontend / controllers文件夹中创建一个控制器文件ChildController.php。

<?php namespace frontend\controllers; use Yii; use app\models\Child; use yii\web\Controller; /** * manual CRUD **/ class ChildController extends Controller { /** * Create */ public function actionCreate() { $model = new Child(); // new record if($model->load(Yii::$app->request->post()) && $model->save()){ return $this->redirect(['index']); } return $this->render('create', ['model' => $model]); } }

步骤3建立检视档案

在frontend / views文件夹中创建一个view文件夹子级。然后在frontend / views / child文件夹中创建一个文件create.php。

<?= $this->render('child_view', [ 'model' => $model, ]) ?>

现在在frontend / views / child文件夹中创建一个文件child_view.php。

<?php use yii\helpers\Html; use yii\widgets\ActiveForm; ?> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'name'); ?> <?= $form->field($model, 'meaning'); ?> <?= $form->field($model, 'gender'); ?> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model-> isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ?> <?php ActiveForm::end(); ?>

步骤4运行

现在, 使用以下URL在浏览器上运行应用程序。

http://localhost/create/frontend/web/index.php?r = child / create

YII插入记录1

查看上面的snpashot, 填充所有字段后, 单击”创建”按钮, 你的数据将被插入数据库。

你可以从phpmyadmin在数据库中检查它。

下载此示例

赞(0)
未经允许不得转载:srcmini » YII数据库:创建(插入)记录示例

评论 抢沙发

评论前必须登录!