Php 使用迭代将值插入数据库

Php 使用迭代将值插入数据库,php,mysql,Php,Mysql,所以在这里,我试图创建一个插入函数,它是动态的。所谓动态,我的意思是它可以插入任何表和n列数。我创建这个函数是为了在需要插入到不同的表或增加列数时,不必编写多个要插入的函数 在我的函数中,我传递了2个参数。一个是表名,第二个是以这种方式排列的列及其值 $arr = array("customerid" => "123", "email" => "asa"); 这是我的功能:- function insert_tester($table,$arr)

所以在这里,我试图创建一个插入函数,它是动态的。所谓动态,我的意思是它可以插入任何表和n列数。我创建这个函数是为了在需要插入到不同的表或增加列数时,不必编写多个要插入的函数

在我的函数中,我传递了2个参数。一个是表名,第二个是以这种方式排列的列及其值

$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不是预期的


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

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

我经常使用这个类,并且认为除了
insert($table,$data)
之外,您可能还会欣赏这些额外的方法:


这正是您需要的,这里$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;
    }
}

试试钥匙上的内爆

implode(', ', array_keys($arr));
对于你的朋友来说,你可以聪明地尝试一下

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

您必须在第一个前缀之前添加前缀,但这应该会让您走上正确的道路

因为您使用的是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中是有效的表或列名。

作为旁注,您确实应该避免将DB连接作为全局数据传递。考虑构建一个DB单例类,它要整洁得多solution@Catharsis好的,我会研究一下。不幸的是,你不能使用
foreach
作为一个表达式。你不需要绑定值,只需在
execute()
期间传递它们,另请参见我的答案。顺便说一句,在这里使用合成更好,即使用PDO db作为依赖项。
$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;
}