输入数组的每个元素作为每个mysql列的记录

时间:2018-02-23 01:05:56

标签: php mysql arrays

我想要的是在我的数据库的字段中输入数组的每个元素这是我的结构示例表记录有四个字段value1,value2 value3,value4我想输入以下代码生成的以下记录

arraynew = array("5878-1","8978-12","2523-1");
$dato1 = "00320555555";
$dato2 = "22/02/2018";
$dato3 = "Maria Mercedes del Barrio";
$dato4 = $arraynew;

$data = array($dato1,$dato2,$dato3,$dato4);

$nuevo = array();
for($i= 0; $i < count($dato4); $i++ ){
    array_push($nuevo, array(
        $data[0],
        $data[1],
        $data[2],
        $data[3][$i]
    ));
}
echo print_r($nuevo);
echo var_dump($nuevo);

这是数组的结构

Array ( [0] => Array ( [0] => 00320555555 [1] => 22/02/2018 [2] => Maria Mercedes del Barrio [3] => 5878-1 ) [1] => Array ( [0] => 00320555555 [1] => 22/02/2018 [2] => Maria Mercedes del Barrio [3] => 8978-12 ) [2] => Array ( [0] => 00320555555 [1] => 22/02/2018 [2] => Maria Mercedes del Barrio [3] => 2523-1 ) ) 1
array (size=3)
  0 => 
    array (size=4)
      0 => string '00320555555' (length=11)
      1 => string '22/02/2018' (length=10)
      2 => string 'Maria Mercedes del Barrio' (length=25)
      3 => string '5878-1' (length=6)
  1 => 
    array (size=4)
      0 => string '00320555555' (length=11)
      1 => string '22/02/2018' (length=10)
      2 => string 'Maria Mercedes del Barrio' (length=25)
      3 => string '8978-12' (length=7)
  2 => 
    array (size=4)
      0 => string '00320555555' (length=11)
      1 => string '22/02/2018' (length=10)
      2 => string 'Maria Mercedes del Barrio' (length=25)
      3 => string '2523-1' (length=6)

我需要的是输入每个数组并将其与相应的字段

连续输入

1 个答案:

答案 0 :(得分:0)

我将假设您正在处理用户提供的数据,因此需要调用mysqli预处理语句。我的方法将对数据库进行3次调用,并记录查询产生的受影响的行数。

(我已经测试过这段代码,以便在我的服务器上取得成功。)

代码:

if(!$mysqli=mysqli_connect($config[0],$config[1],$config[2],$config[3])){
    echo "connection error";
}elseif(!$stmt=$mysqli->prepare("INSERT INTO tablename (value1, value2, value3, value4) VALUES (?,?,?,?)")){
    echo "prepare error ",$mysqli->error;
}else{
    $dato1 = "00320555555";
    $dato2 = "22/02/2018";
    $dato3 = "Maria Mercedes del Barrio";
    $arraynew = ["5878-1","8978-12","2523-1"];
    $stmt->bind_param("ssss",$dato1,$dato2,$dato3,$dato4);
    $tally=0;
    foreach($arraynew as $dato4){  // the declaration of $dato4 is all that is required for binding
        if(!$stmt->execute()){
            echo "execute error @ $dato4";
        }else{
            if($affrows=$mysqli->affected_rows){
                $tally+=$affrows;
            }
        }
    }
    echo $tally;  // output: 3
    $stmt->close();
}