Tuesday, 17 September 2013

Insert Multi Row Data into Multi Column Database Table

Insert Multi Row Data into Multi Column Database Table

Text file containing sets of three data items delimited by ; to be
inserted in three columns of mysql database table is being inserted in a
single column. Found a snippet of code on SO and modified it according to
requirement, but still doesn't work as required. Any idea what could be
wrong? Thanks!
mem.txt
one
two
three;
four
five
six;
...
test.php
<?php
$db = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$db) {
die('Could not connect: ' . mysql_error());
}
$filename = "mem.txt";
$handle = fopen($filename, 'r');
$data = fread($handle, filesize($filename));
$rowsArr = explodeRows($data);
function explodeRows($data) {
$rowsArr = explode(";", $data);
return $rowsArr;
}
for($i=0;$i<count($rowsArr);$i++) {
$cols = explodeRows($rowsArr[$i]);
mysql_select_db("test", $db);
$query = sprintf('INSERT INTO voter (fname, lname, add) VALUES ("%s",
"%s", "%s")', $cols[0], $cols[1], $cols[2]);
if (!mysql_query($query,$db))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
fclose($handle);
mysql_close($db);
?>
output with above :
fname | lname | add
one | |
two | |
three | |
---------------------
four | |
five | |
six | |
---------------------
...
error with above code
Notice: Undefined offset: 1 in C:\xampp\htdocs\test.php on line 20
Notice: Undefined offset: 2 in C:\xampp\htdocs\test.php on line 20
1 record added
output required
fname |lname |add
one | two |three
---------------------
four | five |six
---------------------
...

No comments:

Post a Comment