dsakktdog498483070 2012-07-31 17:58
浏览 87
已采纳

PHP PDO插入具有未知数量变量的函数

Trying to build a function that can insert into a SQL database regardless of how many or how few variables there are. Currently my function is not working.

function insert($table, $columns, $results){
    global $dbh;
    $results = explode(',',$results); 
    $val= ''; 
    $ex = '';
    foreach($results as $result){ 
        $val .= ":" . $result . ","; 
        $ex = "':" . $result . "' => $result,"; 
    }
    $val = rtrim($val, ','); 
    $ex = rtrim($ex, ',');
    $sql = "INSERT INTO $table ($columns) VALUES ($val)";
    $q = $dbh->prepare($sql);
    $q->execute(array($ex));
}

Called like this: insert('users','email,pwd,forename,surname,level,status',$vals);

Where as I managed to get it working for my Select function.

function check($table,$columns,$results){
    global $dbh;
    $columns = explode(',',$columns);
    $results = explode(',',$results); 
    $whr= ''; 
    $int = 0;
    foreach($columns as $column){ 
        $whr.= " AND " . $column . " = '{$results[$int]}'"; 
        $int += 1; 
    }
    $sql = "SELECT * FROM $table WHERE status != 'D' $whr";
    $return = 0;
    foreach($dbh->query($sql) as $check){ 
        $return = 1; 
    } 
    return $return;
}
  • 写回答

2条回答 默认 最新

  • dpf7891 2012-07-31 18:11
    关注

    First, I would probably pass your columns and values into the function as an associative array. This helps force the fact that the function caller must pass an equal number of both. At the very least you should have logic that compares the number of the passed in columns and value elements to make sure they are equal. You might try something like this (note I am also passing the DB connection in as a parameter, which is better coding practice).

    function insert($db, $table, $key_value_array) {
        $sql = 'INSERT INTO ' . $table . ' '; 
        $columns = '(';
        $values = '(';
        foreach ($key_value_array as $k => $v) {
            $columns .= '`' . $k . '`, ';
            $values .= "'" . $v . "', ";
        }
        $columns = rtrim($columns, ', ') . ')';
        $values = rtrim($values, ', ') . ')';
        $sql .= $columns . ' VALUES ' . $values;
        $q = $db->prepare($sql);
        $q->execute();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建