I have a CSV file with contacts. I want to import these contacts into an sqlite database. How can I read the file and insert it into the database?
I have a CSV file with contacts. I want to import these contacts into an sqlite database. How can I read the file and insert it into the database?
You can use the fgetcsv function.
Here is an example usage, assuming a CONTATO(Nome, Funcao, Morada)
table and a line in the CSV of type costa;Programador;Lisboa;
:
<?php
if ($db = sqlite_open("c:/teste.db", 0666, $error)) {
echo "Banco de dados aberto...";
} else {
die ($error);
}
$row = 1;
if (($handle = fopen("teste.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
echo "<p> $num campos na linha $row: <br /></p>\n";
$row++;
$query = "INSERT INTO CONTATO (Nome, Funcao, Morada) VALUES(";
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
// Inserindo os dados no banco.
$query .= "'" . mysql_real_escape_string($data[$c]) . "'";
if ($c+1 < $num) {
$query .= ",";
}
}
$query .= ")";
sqlite_query($db, $query);
}
fclose($handle);
}
?>