Hongmu Notes
Home Language Notes PHP queries the MySQL database, obtains each table, and then outputs the first eight data of each table.
Language Notes PHP mySql

PHP queries the MySQL database, obtains each table, and then outputs the first eight data of each table.

PHP queries the MySQL database, obtains each table, and then outputs the first eight data of each table.

phpcode

<?php
/**
 * 导出 MySQL 数据库的表结构及每个表的前 8 条数据
 * 数据按 id 倒序(若无 id 则按主键/第一列倒序)
 * 数据库:111,用户名:11111,密码:1111
 */

$host = 'localhost';
$user = '1111';
$pass = '11111111111111111';
$dbname = '111';

$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
$conn->set_charset("utf8mb4");

// 输出文件头
echo "-- 导出数据库: $dbname\n";
echo "-- 生成时间: " . date('Y-m-d H:i:s') . "\n";
echo "-- 每个表导出前 8 条数据,按 id(或主键/首列)倒序排列\n\n";
echo "SET FOREIGN_KEY_CHECKS=0;\n\n";

// 获取所有表
$tablesResult = $conn->query("SHOW TABLES");
if (!$tablesResult) {
    die("获取表列表失败: " . $conn->error);
}

while ($row = $tablesResult->fetch_row()) {
    $table = $row[0];

    // 1. 导出表结构
    $createResult = $conn->query("SHOW CREATE TABLE `$table`");
    if (!$createResult) {
        echo "-- 无法获取表 `$table` 的结构,跳过\n\n";
        continue;
    }
    $createRow = $createResult->fetch_assoc();
    $createSQL = $createRow['Create Table'];

    echo "-- 表结构: `$table`\n";
    echo "DROP TABLE IF EXISTS `$table`;\n";
    echo $createSQL . ";\n\n";

    // 2. 获取表的列名,确定排序字段(优先 id,其次主键,最后第一列)
    $colsResult = $conn->query("SHOW COLUMNS FROM `$table`");
    $colNames = [];
    while ($col = $colsResult->fetch_assoc()) {
        $colNames[] = $col['Field'];
    }
    $orderCol = null;
    if (in_array('id', $colNames)) {
        $orderCol = 'id';
    } else {
        // 尝试获取主键
        $pkQuery = $conn->query("SHOW KEYS FROM `$table` WHERE Key_name = 'PRIMARY'");
        if ($pkQuery && $pkQuery->num_rows > 0) {
            $pkRow = $pkQuery->fetch_assoc();
            $orderCol = $pkRow['Column_name'];
        } else {
            // 取第一列(如果存在)
            $orderCol = $colNames[0] ?? null;
        }
    }

    // 构建 ORDER BY 子句
    $orderClause = $orderCol ? "ORDER BY `$orderCol` DESC" : "";

    // 3. 导出前 8 条数据(按指定字段倒序)
    $dataResult = $conn->query("SELECT * FROM `$table` $orderClause LIMIT 8");
    if (!$dataResult) {
        echo "-- 无法查询表 `$table` 的数据,跳过\n\n";
        continue;
    }

    if ($dataResult->num_rows > 0) {
        // 获取字段列表
        $fields = $dataResult->fetch_fields();
        $fieldNames = array_map(function($f) {
            return "`" . $f->name . "`";
        }, $fields);
        $fieldList = implode(", ", $fieldNames);

        // 组装多行 INSERT
        $insertPrefix = "INSERT INTO `$table` ($fieldList) VALUES ";
        $rows = [];
        while ($dataRow = $dataResult->fetch_assoc()) {
            $values = [];
            foreach ($dataRow as $key => $val) {
                if ($val === null) {
                    $values[] = "NULL";
                } else {
                    $escaped = $conn->real_escape_string($val);
                    $values[] = "'" . $escaped . "'";
                }
            }
            $rows[] = "(" . implode(", ", $values) . ")";
        }
        echo $insertPrefix . implode(", ", $rows) . ";\n\n";
    }
    $dataResult->free();
}

$tablesResult->free();
echo "SET FOREIGN_KEY_CHECKS=1;\n";
$conn->close();

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 140
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 187
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 231

Recommended reading

Brand Strategy and Design Agency General Website Template – 1121

Brand Strategy and Design Agency General Website Template – 1121 Practical Collection Yiyou template

An eYouCMS template designed for general-purpose websites intended for brand strategy and design agencies. Its creative and professional design style effectively showcases brand strategy projects, design case studies, creative concepts, and service offerings. This template helps brand strategy firms demonstrate their professional expertise online and attract corporate clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS | eYou...
👁 67
Home & Kitchen Appliances Website Template 0881

Home & Kitchen Appliances Website Template 0881 Practical Collection Yiyou template

This EyouCMS template is ideal for the home furnishings, kitchenware, and electrical appliances industries. Its modern and practical design effectively showcases kitchen appliances, household products, and brand images. It helps home appliance brands showcase their products online and attract home consumers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (...
👁 51
Responsive Fire Extinguisher and Dry Powder Firefighting Equipment Website Template 0622

Responsive Fire Extinguisher and Dry Powder Firefighting Equipment Website Template 0622 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for companies specializing in fire extinguishers, dry powder fire suppression systems, and firefighting equipment. Its eye-catching and professional design effectively showcases firefighting products, safety equipment, and project case studies. It enables firefighting equipment manufacturers to showcase their products online and attract both corporate and government procurement opportunities. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | Eyou...
👁 53
Vocational Education and Training Institution Website Template 0374

Vocational Education and Training Institution Website Template 0374 Practical Collection Yiyou template

An EyouCMS website template designed specifically for vocational education and training institutions. Its professional educational design enables effective presentation of vocational courses, training programs, employment services, and faculty resources. This template helps vocational training organizations attract learners online and enhance their brand awareness. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 39
QQ Personal Space – Blog/News Website Template 0136

QQ Personal Space – Blog/News Website Template 0136 Practical Collection Yiyou template

An eYouCMS template designed for QQ Personal Space, blog/chronicle websites, and news/information platforms. Its fresh and artistic design makes it ideal for hosting emotional journals, personalized signatures, engaging blog posts, and real-time updates. This template helps individual webmasters or bloggers build personalized content-sharing platforms. Template Preview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS | eYou...
👁 29
(PC+WAP) calligraphy and painting website template calligraphy and painting mounting website source code download 1059

(PC+WAP) calligraphy and painting website template calligraphy and painting mounting website source code download 1059 Practical Collection pbootcms Template

A PbootCMS website template for calligraphy, painting, and artwork mounting services, compatible with both PC and WAP devices. Featuring a classical artistic design, this template is ideal for calligraphy and painting studios or galleries showcasing their works and providing mounting services. It enables artists to display their works online, attracting collectors and enthusiasts. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 60