使用迭代将值插入db

时间:2015-06-16 08:38:57

标签: php mysql

所以我在这里尝试制作一个动态的插入函数。动态我的意思是它可以插入任何表格和 n 列数。我正在创建这个函数,这样每当我必须插入不同的表或增加列数时,我就不必编写多个函数来插入。

在我的功能中,我传递 2 参数。一个是 tablename ,第二个是以这种方式列和它们的值的数组。

$arr = array("customerid" => "123", 
              "email" => "asa");

这是我的功能: -

function insert_tester($table,$arr)
    {
        global $conn;
        $val=0;
        try
        {
            $s = $conn->prepare("INSERT INTO $table(" . foreach($arr as $column => $valule) {$column.","} . ") 
                                VALUES(" . foreach($arr as $column => $value) {':val'.$val++} . ")");
            $val=0;
            foreach($arr as $column => $value)
            {
                $s->bindParam(":val$val", $value);
                $val++;
            }
            if($s->execute())
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }//function

但不幸的是,我的功能不起作用,它说foreach没有预料到。

实现目标的最佳和正确方法是什么?

4 个答案:

答案 0 :(得分:1)

这正是您所需要的,这里$ db是您的PDO数据库连接对象     

function insert_tester($db, $table, $arr) {
    $fields = array_keys($arr);
    $values = array_values($arr);
    //build the fields
    $buildFields = '';
    if (is_array($fields)) {
        //loop through all the fields
        foreach ($fields as $key => $field) {
            if ($key == 0) {
                //first item
                $buildFields .= $field;
            } else {
                //every other item follows with a ","
                $buildFields .= ', ' . $field;
            }
        }
    } else {
        //we are only inserting one field
        $buildFields .= $fields;
    }

    //build the values
    $buildValues = '';
    if (is_array($values)) {
        //loop through all the fields
        foreach ($values as $key => $value) {
            if ($key == 0) {
                //first item
                $buildValues .= '?';
            } else {
                //every other item follows with a ","
                $buildValues .= ', ?';
            }
        }
    } else {
        //we are only inserting one field
        $buildValues .= ':value';
    }

    $prepareInsert = $db->prepare('INSERT INTO ' . $table . '(' . $buildFields . ') VALUES (' . $buildValues . ')');

    //execute the update for one or many values
    if (is_array($values)) {
        $prepareInsert->execute($values);
    } else {
        $prepareInsert->execute(array(':value' => $values));
    }
    //record and print any DB error that may be given
    $error = $prepareInsert->errorInfo();
    if ($error[1]) {
        print_r($error);
    } else {
        return true;
    }
}

答案 1 :(得分:1)

由于您正在使用PDO,因此有一种更简单的方法:

$names  = join(',', array_keys($arr));
$values = substr(str_repeat(',?', count($arr)), 1);
$s = $conn->prepare("INSERT INTO $table ($names) VALUES ($values)");
if ($s->execute(array_values($arr))) {
    return true;
}

这假定您的数组键和$table是SQL中的有效表或列名。

答案 2 :(得分:0)

我实际上创建了一个扩展PDO的类,以便我可以做你想做的事情。在实例化数据库连接时,请使用此类而不是PDO。然后,您将能够直接在数据库连接实例(即$conn->insert('sometable', array() );)上使用insert,update和delete方法。

我经常使用这个课程,并认为你可能会欣赏insert($table, $data)以外的奖励方法:

class DatabaseConnection extends PDO {

    public function insert($table, $data) {

        $fields = implode(", ", array_keys($data));
        $questionMarks = rtrim( str_repeat("?, ", count($data)), ", ");
        $stmt = $this->prepare("INSERT INTO $table ($fields) VALUES ($questionMarks)");
        foreach (array_values($data) as $key => $value) {
            $stmt->bindValue($key+1, $value);
        }

        //return $stmt;
        return $stmt->execute();
    }

    public function update($table, $data, $conditions) {

        $fields = implode("=?, ", array_keys($data))."=?";

        foreach ($conditions as $column => $condition) {
            if (empty($whereClause)) {
                $whereClause = "$column=?";
            } else {
                $whereClause .= " AND $column=?";
            }
            $data[] = $condition;
        }

        $stmt = $this->prepare("UPDATE $table SET $fields WHERE $whereClause");

        foreach (array_values($data) as $key => $value) {
            $stmt->bindValue($key+1, $value);
        }

        //return $stmt;
        return $stmt->execute();
    }

    public function delete($table, $conditions) {

        $data = array();

        foreach ($conditions as $column => $condition) {
            if (empty($whereClause)) {
                $whereClause = "$column=?";
            } else {
                $whereClause .= " AND $column=?";
            }
            $data[] = $condition;
        }

        $stmt = $this->prepare("DELETE FROM $table WHERE $whereClause");

        foreach (array_values($data) as $key => $value) {
            $stmt->bindValue($key+1, $value);
        }

        //return $stmt;
        return $stmt->execute();
    }

}

答案 3 :(得分:0)

尝试按键上的内爆

implode(', ', array_keys($arr));

对于你的bindParms,你可以聪明并尝试

implode(', :', array_keys($arr));

你必须在第一个前加上前缀,但这应该让你走上正确的轨道