Seef
Seef

Reputation: 91

How to insert arrays into mysql using php

I am scraping data and then turning the data into arrays that output as follows:

array(8) {   
           [0]=> array(8) {   
                             [1]=> string(1) "1"   
                             [2]=> string(8) "Henricho"   
                             [3]=> string(10) "Bruintjies"   
                             [4]=> string(2) "23"   
                             [5]=> string(3) "Agn"   
                             [6]=> string(6) "10.17A"   
                             [7]=> string(4) "-0.2"   
                             [8]=> string(1) "8" }  
           [1]=> array(8) {   
                             [1]=> string(1) "2"   
                             [2]=> string(5) "Akani"   
                             [3]=> string(7) "Simbine"   
                             [4]=> string(2) "23"   
                             [5]=> string(3) "Agn"   
                             [6]=> string(6) "10.21A"   
                             [7]=> string(4) "-0.2"   
                             [8]=> string(1) "7" } 

It is displayed by using var_dump($results);

Is there a simple way to input the data into a sql table using $results?

Upvotes: 0

Views: 79

Answers (2)

gentle
gentle

Reputation: 60

The data you used var_dump on to give the above result in my guess would be:

$result = array(
array("1","Henricho","Bruintjies","23","Agn","10.17A","-0.2","8"),  
array("2","Akani" , "Simbine" ,"23" ,"Agn", "10.21A","-0.2","7" )
); 

lets assume the fields you want to insert data to are id, firstname, lastname, age, anotherfield,anotherfield,anotherfield,anotherfield

foreach ($result AS $innerArray){
// In above $result, each $innerArray is an indexed array
    $sqlQuery = 'INSERT INTO `tablename` (`id`, `firstname`, `lastname`, `age`, `anotherfield`, `anotherfield`, `anotherfield`, `anotherfield`) VALUES('.implode(",", $innerArray).')';
// You can now execute your sql query depending on the mysql adapter you are using.

}

Upvotes: 0

Luthando Ntsekwa
Luthando Ntsekwa

Reputation: 4218

You need to you something like:

foreach ($results as $value){  
    $allValues = implode('", "', $value); 
    //the above line will give us something like ("1", "Henricho"....etc)
    $query ='Insert into(col1, col2, col3, col4, col5, col6, col7, col8)  
         Values("'.$allValues.'")';
    //You can now execute your query
    echo $query."<BR />";
}    

Check Demo Here

Upvotes: 2

Related Questions