netishix
netishix

Reputation: 193

Massive SQL row insert

I have to load some location strings in an SQL database, but there are too many to insert every single row manually. So I wanted to set all the strings in a single textarea, and once the form is submitted serialize all the data. Something like this:

TEXTAREA DATA

Buenos Aires
Catamarca
Chaco
Chubut
Capital Federal
Córdoba
Corrientes
Entre Rios
Formosa
Jujuy
La Pampa
La Rioja
Mendoza
Misiones
Neuquén
Río Negro
Salta
San Juan
San Luis
Santa Cruz
Santa Fe
Santiago Del Estero
Tierra Del Fuego
Tucumán

And once there identify every single string with PHP in order to then insert it in the database. How do I achieve this?

Upvotes: 1

Views: 91

Answers (3)

VolkerK
VolkerK

Reputation: 96159

You could use a prepared statement* to reduce some of the load on the database server.

$stmt = $pdo->prepare('INSERT INTO yourtable (thefield) VALUE (?)');
$stmt->bindParam(1, $loc);

$locations = preg_split('![\r\n]+!', $theTextAreaValue, -1,  PREG_SPLIT_NO_EMPTY);
foreach($locations as $loc)
    $stmt->execute();
}

also have a read of


edit: *) and you get protection against sql injection's for this kind of queries as well.

Upvotes: 1

Dariusz Majchrzak
Dariusz Majchrzak

Reputation: 1237

$from_textarea = $_POST['text_area_name_attribute'];
$array = explode("\n" , $from_textarea);

foreach($array as $k => $v) {
    mysql_query("insert into table_name(column_name) values('".trim($v)."') ");   
}

Upvotes: 0

Bernhard
Bernhard

Reputation: 1870

 if(isset($_POST['data'])){
  $lines  = explode("\n", $_POST['data']);
  $lines  = array_map('trim', $lines);
  $lines  = implode("'), ('", $lines);
  $query = "INSERT INTO table (field) VALUES ('".$lines."');";  
 }

Upvotes: 0

Related Questions