bootstraptable php 返回json 完整代码
时间: 2023-07-25 13:08:41 浏览: 183
Bootstrap 填充Json数据的实例代码
下面是一个使用 PHP 返回 JSON 数据的 Bootstrap Table 的完整代码示例:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Bootstrap Table</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.staticfile.org/bootstrap-table/1.11.1/bootstrap-table.min.js"></script>
<script src="https://cdn.staticfile.org/bootstrap-table/1.11.1/locale/bootstrap-table-zh-CN.min.js"></script>
</head>
<body>
<table id="table" data-toggle="table" data-url="data.php" data-pagination="true" data-side-pagination="server" data-page-size="10">
<thead>
<tr>
<th data-field="id">ID</th>
<th data-field="name">Name</th>
<th data-field="price">Price</th>
</tr>
</thead>
</table>
</body>
</html>
```
PHP 代码(data.php):
```php
<?php
require_once 'db.php';
function getProducts($offset, $limit) {
$db = connectDb();
$sql = "SELECT * FROM products LIMIT $offset, $limit";
$result = $db->query($sql);
$products = array();
while ($row = $result->fetch_assoc()) {
$products[] = $row;
}
return $products;
}
function countProducts() {
$db = connectDb();
$sql = "SELECT COUNT(*) FROM products";
$result = $db->query($sql);
$row = $result->fetch_row();
return $row[0];
}
$offset = isset($_GET['offset']) ? $_GET['offset'] : 0;
$limit = isset($_GET['limit']) ? $_GET['limit'] : 10;
$products = getProducts($offset, $limit);
$total = countProducts();
$data = array(
'total' => $total,
'rows' => $products
);
echo json_encode($data);
?>
```
db.php 文件内容:
```php
<?php
function connectDb() {
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
?>
```
注意:上面的代码示例中,假设你的数据库名为 test,用户名为 root,密码为 123456,数据表名为 products,数据表结构如下:
```sql
CREATE TABLE products (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
price FLOAT NOT NULL
);
```
你需要根据实际情况修改数据库连接信息,并且创建相应的数据表。
阅读全文