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

如何使用PHP和SQL插入含子分类的JSON格式分类数据?

处理分类JSON数据并更新SQL表的正确实现

我来帮你修正代码,让它正确处理你的分类JSON数据,实现主分类和子分类的关联存储。首先明确你的核心需求:

  • 将JSON中的主分类条目(如ID为21、6、5的条目)存入ads_categories表,它们的category_parent设为NULL,category_root设为自身ID
  • 若主分类包含children数组,子分类的category_parent设为对应主分类的ID,category_root也设为主分类的ID
  • 同时维护category_order字段,按遍历顺序递增

原代码的问题分析

  1. 逻辑结构不匹配:你的输入是嵌套的JSON数组,但原代码假设$_POST['category']是分类ID与父分类标识的键值对,无法正确解析children子数组
  2. SQL注入风险:直接将变量拼接进SQL语句,存在安全隐患
  3. 根分类处理逻辑复杂且不符合需求场景

修正后的实现代码

if(isset($_POST['category'])){
    // 验证Session key(保留你的原有验证逻辑)
    if(in_array($_GET['key'], $_SESSION['key'])){
        unset($_SESSION['key'][array_search($_GET['key'], $_SESSION['key'])]);
        
        // 1. 解析JSON数据为PHP数组
        $categoryData = json_decode($_POST['category'], true);
        if(!is_array($categoryData)){
            echo 'Invalid JSON data';
            exit;
        }

        $i = 1;
        // 2. 使用预处理语句防止SQL注入
        $stmt = mysqli_prepare($db, "UPDATE ads_categories 
                                     SET category_order = ?, category_parent = ?, category_root = ? 
                                     WHERE category_id = ?");
        
        // 绑定参数(i:整数,s:字符串,这里都是整数)
        mysqli_stmt_bind_param($stmt, "iiii", $order, $parent, $root, $catId);

        // 3. 遍历每个主分类条目
        foreach($categoryData as $mainCat){
            $mainCatId = intval($mainCat['id']);
            
            // 处理主分类:parent为NULL,root为自身ID
            $order = $i++;
            $parent = null;
            $root = $mainCatId;
            $catId = $mainCatId;
            mysqli_stmt_execute($stmt);

            // 4. 处理子分类(如果存在children数组)
            if(isset($mainCat['children']) && is_array($mainCat['children'])){
                foreach($mainCat['children'] as $childCat){
                    $childCatId = intval($childCat['id']);
                    
                    $order = $i++;
                    $parent = $mainCatId; // 子分类的parent是主分类ID
                    $root = $mainCatId;   // 子分类的root和主分类一致
                    $catId = $childCatId;
                    mysqli_stmt_execute($stmt);
                }
            }
        }

        mysqli_stmt_close($stmt);
        echo 'Success';
    }else{
        echo 'Error: Invalid key';
    }
}else{
    echo 'Error: No category data received';
}

代码说明

  • JSON解析:先将POST过来的JSON字符串解码为PHP数组,确保数据格式正确
  • 预处理语句:使用mysqli_prepare和参数绑定,彻底避免SQL注入风险
  • 主分类处理:每个主分类的父分类设为NULL,根分类设为自身ID,排序值递增
  • 子分类处理:遍历主分类的children数组,将子分类的父分类和根分类都设为主分类ID,排序继续递增
  • Session验证:保留了你原有Key验证逻辑,确保操作的合法性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:26:41