PDA

View Full Version : Batch add records to database



guvenck
01-08-2007, 05:12 PM
I would like to create an option on my admin page to add batch records to Mysql database.

I guess I need a textarea, a field limiter and a line break :)

After the form has been submitted, the script should parse the data into arrays and add each array value to the database, most probably with a loop.

Can someone help me here? Example:

books

title | year | author

And what if I want to upload and insert CSV format (without phpmyadmin)?

whizard
01-08-2007, 06:16 PM
Not sure exactly what you mean, but here's my best guess:

You want to have a textarea where you can insert data for multiple database rows.

You have a database with the fields title, year, and author.

In your textarea, enter the data like this:

title-year-author;title2-year2-author3;title3-year3-author3; and so on

then use this code:


$row = explode(";",$_POST['textarea']);
foreach($row)
{
$field = explode("-",$row);
$query = "INSERT INTO `tablename` (`title`,`year`,`author`) VALUES '{$field[0]}','{$field[1]}',{$field[2]}'";
//Run query
}


HTH,
Dan

guvenck
01-08-2007, 07:16 PM
It's almost like it. Except each record row will be seperated with a line break and the seperator should be something unique like :: or | etc.

An example of a textarea input:

HONEYMOON|2006|James Patterson
GONE|2005|Lisa Gardner
S IS FOR SILENCE|Sue Grafton

So maybe your code can be modified like this:



$row = explode("\n",$_POST['textarea']);
foreach($row)
{
$field = explode("|",$row);
$query = "INSERT INTO `tablename` (`title`,`year`,`author`) VALUES '{$field[0]}','{$field[1]}',{$field[2]}'";
//Run query
}



And I am curious about a CSV import.

whizard
01-08-2007, 07:38 PM
Yeah that should work... I haven't tested it or anything, but it looks good enough to me...

Dan

marek_mar
01-08-2007, 07:54 PM
MySQL allows inserting more than one row in one query (newer MySQL varsions that is).


INSERT INTO table ('column1', 'column 2', ...) VALUES
(1, 2, ...),
(3, 4, ...),
...