dongxun7301 2016-08-30 11:19
浏览 37
已采纳

重构以循环mySQL和PHP代码

I currently have an associative array called fields that stores all my $_POST variables from my HTML input fields. The associative array variables are used when I try to bind my values to the mySQL database In the same manner, I also have the same names used as column headers for the mySQL database. So this is very tedious and long. Is there a way to perhaps loop through the columns and assign a value with another loop for the associative array? Please check the example below and thank you in advance for your help.

     try {
                $insertSql = "INSERT INTO tableExample";
                $sqlCols = " (
                    a,
                    b,
                    c,
                    d,
                    e,
                    f,
                    g,
                    h,
                    i,
                    j,
                    k,
                    l,
                    m,
                    n,
                    o,
                    p,
                    q,
                    r,
                    s,
                    t,
                    u,
                    v,
                    w,
                    x
                )";
                $result = $db->prepare($insertSql . $sqlCols . " VALUES (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    ?)");
                $result->bindValue(1,$fields['a'],PDO::PARAM_STR);
                $result->bindValue(2,$fields['b'],PDO::PARAM_STR);
                $result->bindValue(3,$fields['c'],PDO::PARAM_STR);
                $result->bindValue(4,$fields['d'],PDO::PARAM_STR);
                $result->bindValue(5,$fields['e'],PDO::PARAM_STR);
                $result->bindValue(6,$fields['f'],PDO::PARAM_STR);
                $result->bindValue(7,$fields['g'],PDO::PARAM_STR);
                $result->bindValue(8,$fields['h'],PDO::PARAM_STR);
                $result->bindValue(9,$fields['i'],PDO::PARAM_STR);
                $result->bindValue(10,$fields['j'],PDO::PARAM_STR);
                $result->bindValue(11,$fields['k'],PDO::PARAM_STR);
                $result->bindValue(12,$fields['l'],PDO::PARAM_STR);
                $result->bindValue(13,$fields['m'],PDO::PARAM_STR);
                $result->bindValue(14,$fields['n'],PDO::PARAM_STR);
                $result->bindValue(15,$fields['o'],PDO::PARAM_STR);
                $result->bindValue(16,$fields['p'],PDO::PARAM_STR);
                $result->bindValue(17,$fields['q'],PDO::PARAM_STR);
                $result->bindValue(18,$fields['r'],PDO::PARAM_STR);
                $result->bindValue(19,$fields['s'],PDO::PARAM_STR);
                $result->bindValue(20,$fields['t'],PDO::PARAM_STR);
                $result->bindValue(21,$fields['u'],PDO::PARAM_STR);
                $result->bindValue(22,$fields['v'],PDO::PARAM_STR);
                $result->bindValue(23,$fields['w'],PDO::PARAM_STR);
                $result->bindValue(24,$fields['x'],PDO::PARAM_STR);
                $result->execute();
            } catch (Exception $e) {
                echo "Unable to store data";
                echo $e->getMessage();
                exit;
            }           
  • 写回答

1条回答 默认 最新

  • dongtong2021 2016-08-30 11:39
    关注

    Quickly cooked up a possible solution. Before trying it, please bear in mind that it's untested and there may be several syntax errors here (no PDO on my end... Actually, no php either).

    What this does is define two separate maps: one for "database columns to indexes" and other for "database columns to values".

    I can't be sure that this solves your problem but it's a starting point.

    <?php
    try 
    {
        //Define your columns and indexes...
        $fields=['col_a' => 1, 'col_b' => 2, 'col_c' => 3, 'col_d' => 4];
    
        //Let this be your post data. Notice how the index are the same as above.
        $data=['col_a' => "Value a", "col_b" => 33, "col_c" => "Value C", "col_d" => 12];
    
        //Prepare the statement....
        $sqlCols=null;
        $sqlValues=null;
    
        foreach($fields as $key => $value) 
        {
            $sqlCols.=$key.',';
            $sqlValues.='?,';
        }
    
        $result = $db->prepare("INSERT INTO tableExample (".substr($sqlCols, 0, -1).") VALUES (".substr($sqlValues, 0, -1).")";
    
        //Bind the values... Please, make sure the order of parameters is correct!.
        foreach($fields as $key => $index)
        {
            $result->bindValue($index, $data[$key], PDO::PARAM_STR);
        }
    
        $result->execute();
    } 
    catch (Exception $e) 
    {
        echo "Unable to store data";
        echo $e->getMessage();
    }
    ?>
    

    Again, let me state that you're exposing your database structure through the names in your post variables. I doubt that's what you want to do.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题