You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter视图页面展示MySQL数据库总表大小

在CodeIgniter中展示MySQL数据库总表大小的方法

要让你提供的SQL语句在CodeIgniter中生效并展示数据库总表大小,可通过以下步骤实现:

1. 在控制器中执行SQL查询

直接使用CodeIgniter的数据库查询方法执行目标SQL,将结果传递给视图:

public function display_database_size() {
    // 目标SQL语句
    $sql = "SELECT table_schema 'Data Base Name',
            sum(data_length + index_length)/1024/1024 'Data Base Size in MB',
            sum(data_free)/1024/1024 'Free Space in MB'
            FROM information_schema.TABLES
            GROUP BY table_schema";
    
    // 执行查询并获取结果数组
    $db_size_info = $this->db->query($sql)->result_array();
    
    // 将数据传递到视图
    $this->load->view('database_size', ['db_size_info' => $db_size_info]);
}

2. 在视图中展示数据

创建对应的视图文件(比如database_size.php),遍历查询结果并格式化展示:

<h2>数据库空间统计</h2>
<table cellpadding="8" cellspacing="0" border="1">
    <thead>
        <tr>
            <th>数据库名称</th>
            <th>已使用空间(MB)</th>
            <th>剩余空间(MB)</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($db_size_info as $item): ?>
        <tr>
            <td><?= htmlspecialchars($item['Data Base Name']) ?></td>
            <td><?= number_format($item['Data Base Size in MB'], 2) ?></td>
            <td><?= number_format($item['Free Space in MB'], 2) ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

参考:输出MySQL数据库总行数的方法

以下是统计当前数据库所有表总行数的CodeIgniter实现:

<?php
// 获取当前数据库的所有表名
$all_tables = $this->db->list_tables();
$total_row_count = 0;

// 遍历每张表统计行数
foreach ($all_tables as $table) {
    $row_count = $this->db->count_all_results($table);
    $total_row_count += $row_count;
}
?>

<!-- 在视图中输出总行数 -->
<p>数据库总行数:<?= $total_row_count ?></p>

内容的提问来源于stack exchange,提问作者Ferjani_BQ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 15:25:22