所以在这里我试图创建一个动态的插入函数。我所说的动态是指它可以插入任何表和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 不是预期的。
实现我的目标的最佳且正确的方法是什么?
最佳答案
这正是您所需要的,这里 $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;
}
}
关于php - 通过迭代将值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30862609/