Inserting a multi-dimensional php array into a mysql database

前端 未结 8 2010
耶瑟儿~
耶瑟儿~ 2020-12-11 03:36

I have an array from a csv with a similar structure to this:

$array = array(
    array(\'name\', \'age\', \'gender\'),
    array(\'Ian\', 24, \'male\'),
    a         


        
8条回答
  •  庸人自扰
    2020-12-11 03:58

    for this array you could do something as simple as this:

    $array = csv_array(); // this is your array from csv
    
    $col_name = $array[0][0];
    $col_age = $array[0][1];
    $col_gender = $array[0][2];
    
    for($i = 1; $i < count($array); $i++){
        //this is where your sql goes
        $sql = "INSERT INTO `table` ($col_name, $col_age, $col_gender) 
        VALUES($array[$i][0], $array[$i][1], $array[$i][2])";
    
        $db->query($sql);
    }
    

    You should sanitize input, which I didn't do in my example. If your array structure isn't guaranteed to be the same then you'll have to do something else.

提交回复
热议问题