yii2连接数据库,db and controller and view

1、添加数据库连接:由于自身工作一直是用的是mssql,所以对mysql不是很熟悉,不过基础语法都差不多,但是由于电脑问题,只能mysql,mssql不支持连接,谁让咱一直用的xp呢,哎,屌丝。

在config下面有个db.php,只要将你的数据库名称放进去就行了。这边用的是教程里面的表Country,有population、name、code、三个字段

 <?php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=yii2',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
];

2、添加model:此处让我体会到了yii2的优点,但是源码就不分析了,呵呵,谁让咱是新手呢。

<?php
	namespace app\models;
	use Yii;
	use yii\base\Model;
	use yii\db\ActiveRecord;
	
	//此处yii的机制,不需要写其他任何代码,直接通过类名自动关联数据库表,原理机制真不明白,哈哈?
	class Country extends ActiveRecord
	{	
	}

3、添加Controller,此处跟之前例子中的site有区别就是新增了文件夹,将controller放到另外的文件中,但是要保证文件名一致。此处为了分页,使用了pagination,具体使用说明后续补充。

<?php
	namespace app\controllers;
	
	use Yii;
	use yii\web\Controller;
	use yii\data\Pagination;
	use app\models\Country;
	
	class CountryController extends Controller
	{
	        //此处写的时候出现过一个错误:yii2 Unable to resolve the request:原因是将actionIndex写成了actionindex,你说让我这种以前不区分大小写的咋办。
		public function actionIndex()   
		{

			$query = Country::find();
			
			$pagination = new Pagination(
			['defaultPageSize'=>5,'totalCount'=>$query->count(),]
			);

			$countries = $query->orderBy('name')
						->offset($pagination->offset)
						->limit($pagination->limit)
						->all();

			return $this->render('index',[
								'countries' => $countries,
								'pagination' => $pagination,
			]);
		}
	}
	
?>

4、添加view

<?php
	use yii\helpers\Html;
	use yii\widgets\LinkPager;	
?>
<h1>Countries</h1>
<ul>
	<?php	foreach ($countries as $country):	?>
		<li>
		         //此处也出现过错误:{$country->name} ({$country->code}): 数据没刷过来,原因是双引号我写的是单引号,我记得单双在php上不是一样的么,原因没搞懂?
			<?= Html::encode("{$country->name} ({$country->code})") ?>:
			<?= $country->population ?>
		</li>
	<?php endforeach; ?>  //此处也出现过错误:syntax error, unexpected end of file,原因就是endforeach前面的php又被我拉下了。
</ul>

<?= LinkPager::widget(['pagination'=>$pagination])?>


你可能感兴趣的:(yii2连接数据库,db and controller and view)