【发布时间】:2015-04-20 21:46:46
【问题描述】:
我正在使用 Yii 框架开发一个数据库应用程序。我正在从 MySQL 数据库中读取表并将它们显示给用户。我需要用户能够过滤表中的字段或搜索某个值。
例如,我有一个名为“超市”的表:
CREATE TABLE IF NOT EXISTS `supermarkets` (
`Name` varchar(71) NOT NULL,
`Location` varchar(191) DEFAULT NULL,
`Telephone` varchar(68) DEFAULT NULL,
`Fax` varchar(29) DEFAULT NULL,
`Website` varchar(24) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
.../模特/超市:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Supermarkets extends ActiveRecord
{
}
.../views/supermarkets/index.php:
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<?php
$array = (array) $supermarkets;
function build_table($array){
// start table
$html = '<table class="altrowstable" id="alternatecolor">';
// header row
$html .= '<tr>';
foreach($array[0] as $key=>$value){
$html .= '<th>' . $key . '</th>';
}
$html .= '</tr>';
// data rows
foreach( $array as $key=>$value){
$html .= '<tr>';
foreach($value as $key2=>$value2){
$html .= '<td>' . $value2 . '</td>';
}
$html .= '</tr>';
}
// finish table and return it
$html .= '</table>';
return $html;
}
echo build_table($array);
?>
....控制器/超市控制器:
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Supermarkets;
class SupermarketsController extends Controller
{
public function actionIndex()
{
$query = supermarkets::find();
$pagination = new Pagination([
'defaultPageSize' => 20,
'totalCount' => $query->count(),
]);
$supermarkets = $query->orderBy('Name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('index', [
'supermarkets' => $supermarkets,
'pagination' => $pagination,
]);
}
}
我需要用户能够过滤表格或按一个或多个属性搜索其字段。我该怎么做?
【问题讨论】:
-
关于您的数据库表有两点值得一提的是: 1. 不要将列名大写。 2. 使用“id”字段来唯一标识超市。这可以是一个自动增量列。
-
你说得对,谢谢。
标签: php mysql search yii filter