如何用CodeIgniter 4模型和实体从数据库读取数据

148 阅读2分钟

创建数据库

创建名为codeigniter4_db的新数据库。这个数据库有1个表。产品表

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `price` double NOT NULL,
  `quantity` int(11) NOT NULL,
  `status` tinyint(1) NOT NULL,
  `created` date NOT NULL,
  `description` text NOT NULL,
  `category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`name`, `price`, `quantity`, `status`, `created`, `description`, `category_id`) VALUES
('Tivi 1', 20, 4, 1, '2021-07-13', 'good', 1),
('Tivi 2', 63, 15, 0, '2020-08-11', 'good', 1),
('Laptop 1', 24, 12, 1, '2021-08-12', 'good', 2),
('Laptop 2', 60, 34, 1, '2020-08-12', 'good', 2),
('Laptop 3', 23, 27, 0, '2020-08-17', 'good', 3),
('Computer 1', 4.5, 2, 1, '2021-08-20', 'ABC', 3),
('Computer 2', 111, 222, 1, '2021-09-25', 'AAA', 7),
('Computer 3', 33333, 888, 0, '2021-10-11', 'abc', 2),
('ABC', 20, 4, 1, '2021-07-12', 'good', 7),
('ABC', 20, 4, 1, '2021-07-12', 'good', 7),
('ABC', 20, 4, 1, '2021-07-12', 'good', 7),
('ABC', 20, 4, 1, '2021-07-12', 'good', 7),
('ABC', 20, 4, 1, '2021-07-12', 'good', 7);

产品表的结构

产品表的数据

下载并安装CodeIgniter 4

下载最新版本的CodeIgniter 4,并将源代码解压到名为LearnCodeIgniter4WithRealApps的新文件夹。

公共文件夹中的index.phphtaccess文件剪切到项目的文件夹中。

打开文件夹中的index.php,找到第16行,将路径替换为Paths.php文件,如下所示。

$pathsPath = realpath(FCPATH . '/app/Config/Paths.php');

打开app/Config文件夹中的App.php,找到第39行,在$indexPage变量中删除index.php字符串,如下所示。

public $indexPage = '';

设置BASE URL

打开app/Config文件夹中的App.php文件。设置**$baseURL**变量的值,如下所示。

public $baseURL = 'http://localhost:8091/LearnCodeIgniter4WithRealApps/';

配置数据库连接

打开app/Config文件夹中的Database.php文件,添加如下值连接到数据库。

<?php

public $default = [
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'codeigniter4_db',
	'port'     => 3306,
];

创建模型

app/Models文件夹下创建名为ProductModel.php的新PHP文件,如下所示。

<?php

namespace App\Models;

use CodeIgniter\Model;

class ProductModel extends Model
{
	protected $table      = 'product';

	protected $primaryKey = 'id';

	protected $returnType = 'array';

	protected $allowedFields = ['name', 'price', 'quantity', 'status', 'created', 'description'];
}				
			

创建控制器

app/Controllers文件夹下创建名为Demo.php的新PHP文件,如下所示。

<?php

namespace App\Controllers;

use App\Models\ProductModel;

class Demo extends BaseController
{
    public function index()
    {
        $productModel = new ProductModel();
        $data['products'] = $productModel->findAll();
        return view('demo/index', $data);
    }
}

创建视图

app/Views文件夹下创建名为Demo的新文件夹。在这个文件夹中,创建名为index.php的新PHP文件,如下所示。

<html>

	<head>
		<title>Modeling Data and ORM in CodeIgniter 4</title>
	</head>

	<body>

		<h3>Product List</h3>
		<table border="1" cellpadding="2" cellspacing="2">
			<tr>
				<th>Id</th>
				<th>Name</th>
				<th>Status</th>
				<th>Created</th>
				<th>Price</th>
				<th>Quantity</th>
				<th>Description</th>
			</tr>
			<?php foreach ($products as $product) { ?>
				<tr>
					<td><?= $product['id'] ?></td>
					<td><?= $product['name'] ?></td>
					<td><?= $product['status'] ?></td>
					<td><?= $product['created'] ?></td>
					<td><?= $product['price'] ?></td>
					<td><?= $product['quantity'] ?></td>
					<td><?= $product['description'] ?></td>
				</tr>
			<?php } ?>
		</table>

	</body>

</html>

定义路线

打开app/Config文件夹中的Routes.php文件。设置默认的控制器,如下所示。

$routes->get('/', 'Demo::index');
$routes->get('/demo', 'Demo::index');
$routes->get('/demo/index', 'Demo::index');

CodeIgniter 4项目的结构

运行应用程序

用以下网址访问Demo控制器中的索引动作**:http://localhost:8095/LearnCodeIgniter4WithRealApps/demo/index**

輸出