数组到数据库插入PHP MYSQL

时间:2014-02-25 12:45:48

标签: php mysql arrays arraylist multidimensional-array

我有一个复选框,它取一些值,下面一个是我从矩阵表单中获得的post值。现在,我在下面的数组值应该像这样格式化

发布值:

Array (
    [31_1] => on
    [31_2] => on
    [31_3] => on
    [56_2] => on
    [56_4] => on
    [66_1] => on
    [66_3] => on
) 

预期价值:

31=>1,2,3

56=>2,4

66=>1,3

如果我能够将值存储在数据库表(author_book)中,我会很高兴,如下所示:

  S.No      Author_ID       Book_IDs
  1         31              1,2,3
  2         56              2,4
  3         66              1,3

简而言之,post值应存储在DB表中,以便我继续进行。我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:0)

foreach($array_name as $key=> $value)
{

$var1=$key;
$var2=$value;

// here you can have your db statements to insert the values


}

答案 1 :(得分:0)

你走了。可能还有一种较短的方法:

<?php
$array = array (
    '31_1' => 'on',
    '31_2' => 'on',
    '31_3' => 'on',
    '56_2' => 'on',
    '56_4' => 'on',
    '66_1' => 'on',
    '66_3' => 'on',
);

$new_array = array();

foreach($array as $ind=>$val){

    //breaks string at '_' and gets 31 and 1 separately
    $key_val = explode('_',$ind); 

    if(array_key_exists($key_val[0],$new_array)){
            //this is to append if key exists, eg. 31 => 1,2,3
        $new_array[$key_val[0]] = $new_array[$key_val[0]].",".$key_val[1]; 
    }
    else
    {
        $val = $key_val[1];
        $new_array[$key_val[0]] = $val;
    }
}

print_r($new_array);
?>

<强> Fiddle

答案 2 :(得分:0)

我相信您只想插入设置为ON的author_id的值 取消将所有索引设置为OFF

尝试类似的东西:

$books=array();
foreach($array_name as $key=> $value){
    if($value==='on'){
        //prepare the array
        list($author_id,$books[$author_id][])=explode("_",$key)
    }
}

foreach($temp as $k=>$v){        
    $q->query("INSERT INTO author_book(author_id,books_id) VALUES($k,".implode(',',$v)));
}

由于 并不断提问:)

答案 3 :(得分:0)

这段代码会为你构建查询,记得使用一些数据注入预防机制

<?php

$x = array (
"31_1" => "on",
"31_2" => "on",
"31_3" => "on",
"56_2" => "on",
"56_4" => "on",
"66_1" => "on",
"66_3" => "on"
);

$newarray = array();

foreach($x as $key => $val){
$key = explode("_", $key);
$newkey = $key[0];
$newval = $key[1];
$newarray[$newkey][] = $newval;
}

foreach($newarray as $key => $val){
$query = "INSERT INTO (Author_ID, Book_IDs) VALUES (" . $key . ",'" . join(',', $val) . "')";
echo $query . "<br />";
}