Array
(
[0] => Array
(
[emp_name] =>
[emp_title] => Senior Developer
[emp_master_id] => 0
[emp_designation] => TL
[emp_skills] => PHP, MySQL
[emp_experience] => 4-5
[emp_location] => Chennai
)
[1] => Array
(
[emp_name] =>
[emp_title] => Web Developer
[emp_master_id] => 0
[emp_designation] => Senior Developer
[emp_skills] => 10Base-T Switching, PHP
[emp_experience] => 4-5
[emp_location] => Chennai
)
)
我希望使用Foreach在Db中插入数组..任何建议
答案 0 :(得分:1)
假设你的数组名称是$ data
foreach($data as $key => $value){
$sql="Insert into table_name (empname,..... )values('".$value['empname']."',....);";
$result=$conn->query($sql);
}
这应该做的工作,假设您有连接变量,如
$conn = new mysqli($servername, $username, $password, $dbname);
在 sql查询中提供列表名称,如表格。
修改强>
这样做的安全方式是
foreach($data as $key => $value){
// prepare and bind
$stmt = $conn->prepare("INSERT INTO table_name(emp_name, title, ...) VALUES (?, ?, ..)");//No of question marks are equal to columns you have mentioed
$stmt->bind_param("sss", $empName, $title, ...);
// i - integer
// d - double
// s - string
// b - BLOB
// set parameters and execute
$empName= $value['empname'];
$title= $value['title'];
//continue to do it for all...
$stmt->execute();
$stmt->close();
}
$conn->close();
注意:如果您知道如何操作,也可以使用功能,foreach中的代码更少
快乐的编码:)
答案 1 :(得分:-2)
foreach($arr as $v){
$sql = ') VALUES (';
foreach($v as $k => $value){
$sql = ",".$k.$sql.'"'.$value.'",';
}
$sql = 'Insert into table_name ('.trim($sql,',').';';
$result=$conn->query($sql);
}
这可能有效。