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

PHP读取MySQL数据输出空白,数据已存储,求代码问题排查

问题排查与解决方案

核心问题

你的代码读取数据为空,根源在于查询时的员工ID参数无效或未正确传递,导致数据库查询不到匹配记录:

  • 短码参数缺失:如果使用短码时没指定employee_id(比如只写[attendance_record]),$employee_id会是空字符串,$wpdb->prepare会把整数占位符%d解析为0,而你数据库里的员工ID并非0,因此查不到数据。
  • 参数类型不匹配:保存数据时直接用字符串类型的$_POST['employee_id'],若数据库employee_id字段是整数类型,MySQL会自动转换,但查询时%d要求参数是整数,若短码传递的是带非数字字符的字符串,会被解析为0,同样无法匹配。
  • 无空数据提示:查询不到数据时直接输出空表格,没有任何提示,导致页面看起来完全空白。

修复方案

1. 确保短码正确传递参数

使用短码时必须明确指定员工ID,示例:

[attendance_record employee_id="123"]

2. 优化短码查询代码(增加验证与空数据提示)

修改后的函数会先验证参数有效性,查询不到数据时也会给出明确提示:

function attendance_record_shortcode( $atts ) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'employee_attendance';

    // 获取短码参数
    $atts = shortcode_atts( array(
        'employee_id' => ''
    ), $atts );
    $employee_id = trim($atts['employee_id']);

    // 验证员工ID是否有效
    if (empty($employee_id) || !is_numeric($employee_id)) {
        ob_start();
        ?>
        <p>请在短码中指定有效的员工ID,例如:[attendance_record employee_id="123"]</p>
        <?php
        return ob_get_clean();
    }

    // 转换为整数类型,确保与数据库字段匹配
    $employee_id = (int)$employee_id;

    // 查询考勤数据
    $attendance_data = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM $table_name WHERE employee_id = %d",
            $employee_id
        )
    );

    // 输出表格
    ob_start();
    ?>
    <table>
        <thead>
            <tr>
                <th>日期</th>
                <th>状态</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($attendance_data)) : ?>
                <tr>
                    <td colspan="2">暂无该员工的考勤记录</td>
                </tr>
            <?php else : ?>
                <?php foreach ( $attendance_data as $attendance ) : ?>
                    <tr>
                        <td><?php echo esc_html($attendance->date); ?></td>
                        <td><?php echo esc_html($attendance->status); ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
<?php
return ob_get_clean();
}
add_shortcode( 'attendance_record', 'attendance_record_shortcode' );

3. 优化保存代码(确保数据类型正确)

保存数据时将员工ID转换为整数,避免存入无效值:

// 修改保存代码中的employee_id处理逻辑
$employee_id = (int)$_POST['employee_id'];

额外优化:添加安全防护

输出数据时使用esc_html()函数,防止XSS攻击,这是WordPress开发的最佳实践。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:35:21