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

YII数据库读取记录示例

点击下载

现在, 我们将从表子中获取数据。在这里, 我们的Yiii2文件夹被命名为已读。

步骤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] 
        ]; 
    } 
}

步骤2添加要阅读的操作

在ChildController.php文件中, 我们需要添加操作actionIndex以从表中获取数据。

<?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]); 
    } 

    /** 
     * Read 
     */ 
    public function actionIndex() 
    { 
        $child = Child::find()->all(); 
         
        return $this->render('index', ['model' => $child]); 
    }
    }

看上面的代码, 所有代码都是相同的, 只是最后一个操作是获取数据。

步骤3建立检视档案

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

<?php 
use yii\helpers\Html; 
?> 
 
<style> 
table th, td{ 
    padding: 10px; 
} 
</style> 
 
<?= Html::a('Create', ['child/create'], ['class' => 'btn btn-success']); ?> 
 
<table border="1"> 
   <tr> 
        <th>Name</th> 
        <th>Meaning</th> 
        <th>Gender</th> 
    </tr> 
    <?php foreach($model as $field){ ?> 
    <tr> 
        <td><?= $field->name; ?></td> 
        <td><?= $field->meaning; ?></td> 
        <td><?= $field->gender; ?></td> 
        <td><?= Html::a("Edit", ['child/edit', 'id' => $field->id]); ?> | <?= Html::a("Delete", ['child/delete', 'id' => $field->id]); ?></td> 
    </tr> 
    <?php } ?>

步骤4运行

在浏览器上运行它。

http://localhost/read/frontend/web/index.php?r = child%2Findex

YII读记录1

下载此示例

赞(0)
未经允许不得转载:srcmini » YII数据库读取记录示例

评论 抢沙发

评论前必须登录!