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

PHP如何无需重复编码实现多个file_id字段的批量调用逻辑

PHP重复执行逻辑优化方案

修改后的完整可运行代码如下:

if (preg_match('/^\/start (.*)/', $text, $match) or preg_match('/^\/get_(.*)/', $text, $match)) {
    $id = $match[1];
    if (isJoin($from_id)) {
        $fileData = mysqli_query($db, "SELECT * FROM `file` WHERE `id` = '{$id}'");
        $file = mysqli_fetch_assoc($fileData);
        if (mysqli_num_rows($fileData)) {
            if ($file['password']) {
                sendMessage($from_id, "please send pass :", "markdown", $btn_back, $message_id);
                mysqli_query($db, "UPDATE `user` SET `step` = 'password', `getFile` = '$id' WHERE `from_id` = '$from_id'");
            } else {
                // 修复原代码计数逻辑bug:先计算数值再做千分位格式化,避免下载量过千时计数异常
                $downloadsCount = $file['downloads'] + 1;
                $downloads = number_format($downloadsCount);
                $caption = urldecode($file['caption']);

                // 读取数据库存储的循环上限,不需要动态配置的话直接替换为 $maxFileCount = 24; 即可
                $countRes = mysqli_query($db, "SELECT `config_value` FROM `config` WHERE `config_key` = 'max_file_count' LIMIT 1");
                $countRow = mysqli_fetch_assoc($countRes);
                $maxFileCount = (int)$countRow['config_value'];

                // 循环执行发送逻辑,无需重复写代码
                for ($i = 1; $i <= $maxFileCount; $i++) {
                    $fileKey = "file_id" . $i;
                    // 空值校验,避免部分file_idN字段为空时报错
                    if (empty($file[$fileKey])) continue;
                    
                    Ilyad("send{$file['type']}", [
                        'chat_id' => $from_id,
                        $file['type'] => $file[$fileKey],
                        'caption' => "📥 count : <code>{$downloads}</code>\n{$caption}\n Thanks",
                        'parse_mode' => "html",
                    ]);
                }

                mysqli_query($db, "UPDATE `file` SET `downloads` = `downloads`+1 WHERE `id` = '$id'");
                mysqli_query($db, "UPDATE `user` SET `step` = 'none', `downloads` = `downloads`+1 WHERE `from_id` = '$from_id'");
            }
        } else sendMessage($from_id, "hi welcome to bot", 'markdown', $btn_home, $message_id);
    } else {
        joinSend($from_id);
        mysqli_query($db, "UPDATE `user` SET `getFile` = '$id' WHERE `from_id` = '$from_id'");
    }
}

关键说明

  • 动态循环上限需要你提前在数据库建一张配置表,示例用的是config表,包含config_key和config_value两个字段,存入config_key为max_file_count、config_value为你需要的上限数值即可,后续修改上限直接改数据库值不需要动代码
  • 如果你的首个file字段命名为file_id而非file_id1,可以将循环内的字段拼接逻辑调整为:
    $fileKey = $i === 1 ? 'file_id' : 'file_id' . $i;
    
  • 现有代码直接拼接SQL参数存在SQL注入风险,后续建议改用mysqli预处理语句优化安全问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:45:03