我需要使用此数组生成一个mysql插入查询,其中列名是field_name&值是field_values。我尝试使用implode,这里是嵌套数组&困扰我很多。
Array
(
[0] => Array
(
[field_name] => Date
[field_value] => 01/02/2013
)
[1] => Array
(
[field_name] => Time
[field_value] => 03:20 PM
)
[2] => Array
(
[field_name] => submitted_lat
[field_value] => 13.06114
)
[3] => Array
(
[field_name] => submitted_long
[field_value] => 80.2371547
)
[4] => Array
(
[field_name] => submitted_on
[field_value] => 2013-02-01 15:20:10
)
[5] => Array
(
[field_name] => submitted_by
[field_value] => superadmin@gmail.com
)
[6] => Array
(
[field_name] => pdf
[field_value] =>
)
)
答案 0 :(得分:1)
试试这个
$sql = "INSERT INTO `table_name` SET ";
$sql_fields='';
foreach($array_name as $k=>$v){
$sql_fields .= "`".$v['field_name']."`='".$v['field_value']."', ";
}
$sql_fields = substr($sql_fields,0,-2);
$sql .= $sql_fields;
echo $sql;
答案 1 :(得分:0)
一个非常简单的方法是:
$query = 'insert into table ';
foreach($inputs as $input) {
$query .= ' '.$input['field_name'].' = '.$input['field_value'];
}
echo $query;
答案 2 :(得分:-1)
$fields=array();
$values=array();
for($i=0;$i<count($array);$i++)
{
$fields[]=$array[$i]['field_name'];
$values[]=$array[$i]['field_value'];
}
if(count($array) > 0)
{
$query="Insert into tablename (".implode(",", $fields).") values (".implode(",", $values).")";
mysql_query($query);
}
答案 3 :(得分:-1)
您需要确保您的值正确并受到保护,以避免SQL注入。动态构建自己的SQL查询并直接插入数据库是不安全的。
无论如何,你可以使用array_map()做这样的事情:
$arr = array(array("name" => "column1", "value" => "value1"),
array("name" => "column2", "value" => "value2"),
array("name" => "column3", "value" => "value3"));
$columns = array_map(function($item) { return $item['name'];}, $arr);
$values = array_map(function($item) { return "'". $item['value'] . "'";}, $arr);
$columnsList = implode(',', $columns);
$valuesList = implode(',', $values);
$sql = "INSERT INTO mytable($columnsList) VALUES ($valuesList)";