Import particular Colums of csv in database in php/sql - php

I have a CSV which contains 15 columns.
But I want to import only 2 columns from the CSV in database.
whats should I do?
I tried importing but it's importing all the columns.
<?php
//database connection details
$connect = mysql_connect('localhost','root','123456');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('test',$connect);
// path where your CSV file is located
define('CSV_PATH','C:/wamp/www/');
// Name of your CSV file
$csv_file = CSV_PATH . "test.csv";
if (($handle = fopen($csv_file, "r")) !== FALSE) {
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
$col1 = $col[0];
$col2 = $col[1];
$col3 = $col[2];
// SQL Query to insert data into DataBase
$query = "INSERT INTO csvtbl(ID,name,city) VALUES('".$col1."','".$col2."','".$col3."')";
$s = mysql_query($query, $connect );
}
fclose($handle);
}
echo "File data successfully imported to database!!";
mysql_close($connect);
?>

Related

get specific row from csv file when importing into phpmysqladmin

I'm new in here, I'm trying to get a Specific rows for a calendar csv file and import to phpmysql database but could not actually get it, hoping someone can hep me
this is my csv file
this is my database look like, i want to get row 4,6,8...so on from csv file and import to table:calendar, column:day and get row 3,5,7...to the same table but column:date
And this is my code
<?php
include "dbFunctions.php"; //Connect to Database
$deleterecords = "TRUNCATE TABLE calendar"; //empty the table of its current records
mysqli_query($link, $deleterecords);
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." Uploaded Successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
//exclude the first row title
$row = 1;
if(($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($i=0; $i<=38; $i++){
if($firstRow) { $firstRow = false; }
else {
$import="INSERT into class(day, date)
values('$data[0]','$data[1]')";
mysqli_query($link, $import) or die(mysqli_error($link));
}
echo $data[$i] . "<br />\n";
}}
fclose($handle);
}
//view upload form
}else {
print "Upload csv file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='uploadCalendar.php' method='post'>";
print "csv File to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
Since the patterns are odd and even rows.
$row = 0;
$i = 0;
$container = array();
if(($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row > 2) {
if ($row % 2 == 0) {
$i = $i - 6;
$v = 'day';
} else {
$v = 'date';
}
foreach ($data as $column) {
$container[$i][$v] = $column;
$i++;
}
}
$row++;
}
fclose($handle);
}
foreach ($container as $value) {
$import="INSERT into class(day, date)
values('".$value['day']."','".$value['date']."')";
mysqli_query($link, $import) or die(mysqli_error($link));
}
The $container should contain the date paired to the day. Like,
$container = [['day' => 'W1D1', 'date' => '19-Oct'], ['day' => 'W1D2', 'date' => '20-Oct']];
And you can use loop to insert into database.

How can you specify from which column position to start the data import from excel to mysql

Hi guys i have an php excel issue.
The problem is that i have an excel file that has several rows and columns, the deal is that i want to import only from specific row position for example A11 or C12. How can i tell this in php?
Here is the column selection code:
$csv_file = $a;
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
while(! feof($getfile))
{
$data = fgetcsv($getfile, NULL,"\t");
$col1 = $data[0];
$col2 = $data[1];
$col3 = $data[2];
$col4 = $data[3];
$col5 = $data[4];
$col6 = $data[5];
$col7 = $data[6];
$col8 = $data[7];
$query = "INSERT INTO $tableName(cod, den_material, furnizor, cant_reper ,lg, cod_furnizor, obs, data) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."')";
$s=mysql_query($query);
}
Here is the full code:
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 10240) . " Kb<br>";
//echo "Stored in: " . $_FILES["file"]["tmp_name"];
$a=$_FILES["file"]["tmp_name"];
//echo $a;
$tableName = str_replace('.txt','',$_FILES["file"]["name"]);
$connect = mysql_connect('localhost','root','password');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('database_test',$connect);
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tableName."'"))!=1){
$table = mysql_query("CREATE TABLE `$tableName` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`cod` TEXT NOT NULL,
`den_material` TEXT NOT NULL,
`furnizor` VARCHAR(255) NOT NULL,
`cant_reper` VARCHAR(255) NOT NULL,
`lg` VARCHAR(255) NOT NULL,
`cod_furnizor` VARCHAR(255) NOT NULL,
`obs` TEXT(255) NOT NULL,
`data` DATE ,
PRIMARY KEY (`id`)
);");
if(!$table){
die("Upload failed");
}
}
// path where your CSV file is located
//define('CSV_PATH','C:/xampp/htdocs/');
//<!-- C:\xampp\htdocs -->
// Name of your CSV file
$csv_file = $a;
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
while(! feof($getfile))
{
$data = fgetcsv($getfile, NULL,"\t");
$col1 = $data[0];
$col2 = $data[1];
$col3 = $data[2];
$col4 = $data[3];
$col5 = $data[4];
$col6 = $data[5];
$col7 = $data[6];
$col8 = $data[7];
$query = "INSERT INTO $tableName(cod, den_material, furnizor, cant_reper ,lg, cod_furnizor, obs, data) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."')";
$s=mysql_query($query);
}
}
echo "<script>alert('Data succesfully added!');window.location.href='index.php';</script>";
//echo "File data successfully imported to database!!";
}
?>
Hope you cand help me, thanks in advance! :)
Fair warning: I have never used fgetcsv for anything however I understand the principle.
However working from the manual on php.net I have created a loop that starts reading only at the row and col that are specified. I picked random values but you can make them whatever you want. A=0, B=1 and so forth. So I have said something like all data from row 5 and from col C.
<?php
$row = 1;
$mydata = array();
$wantrow = 4;
$wantcol = 2;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data); // number of fields in the line
$row++;
for ($c=0; $c < $num; $c++) {
if($c<$wantcol){
// this is what we do not want
}elseif($row<$wantrow){
// also we do not want this
}else{
// ah-ha, we do want this
$mydata[$row][$c] = $data[$c];
}
}
}
fclose($handle);
}
?>
You would then have a two dimensional array of the values in that section. I have chosen to be a little clumsy looking so you can easily understand the logic of what I am trying to demonstrate.
Actually you could make it fair more readable like this:
if( ($c>=3) && ($row>=5) ){
$mydata[$row][$c] = $data[$c];
}
You could apply further limits with the if statements and set an upper limit too but I am sure you know how to do that.
if( ($c>=3) && ($c<=22) && ($row>=5) && ($row<=6) ){
$mydata[$row][$c] = $data[$c];
}
This would give you square inside of C6 to E23 only.
Also in you application you probably want to do something more useful than just shoving the data into an array. I imagine you probably want to embed the data into SQL or something like that.
YYMV. I have not tested this code but it would be roughly like that.
http://php.net/manual/en/function.fgetcsv.php

Import CSV, exclude first row

I'm importing my csv fine now except one thing, how do i get the import to ignore the data in the first row? Employees will be uploading the same format which has the column names in that first row.
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File " . $_FILES['filename']['name'] . " uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
just set a variable $i = 0 Then only insert when $i = 1 or more
if (isset($_POST['submit'])) {
$i=0; //so we can skip first row
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($i>0) {
$import="INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('".$userinfo['first_name']." ".$userinfo['last_name']."','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
$i++;
}
fclose($handle);
print "Import done";
}
You can simply use MySQL's LOAD DATA INFILE command, which will be considerably faster than parsing the CSV into PHP, constructing an INSERT statement for every record, submitting it as a string to MySQL and having MySQL parse said string for SQL (at risk of SQL injection):
LOAD DATA INFILE ? INTO TABLE tictoc
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
IGNORE 1 LINES
(tasktime, sessiontime, sessionstart, sessionend, sessionnotes)
SET employee = ?, taskname = ?
Using PDO:
$dbh = new PDO('mysql:dbname='.$dbname, $username, $password);
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
$qry = $dbh->prepare('
LOAD DATA INFILE :filepath INTO TABLE tictoc
FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'"\'
IGNORE 1 LINES
(tasktime, sessiontime, sessionstart, sessionend, sessionnotes)
SET employee = :employee, taskname = :taskname
');
$qry->execute(array(
':filepath' => $_FILES['filename']['tmp_name'],
':employee' => $userinfo['first_name'],
':taskname' => $userinfo['last_name']
));
}
maybe you can use this way if you like:
$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$i++;
if($i==1) continue;
$import="INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('".$userinfo['first_name']." ".$userinfo['last_name']."','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
No variable needed. It is much simpler than this. Here is a solution that requires the least amount of foreign code, and works just fine. Try putting:
$headers = fgetcsv($handle, 1000, ",");
Before your while() loop that grabs the CSV data. That grabs the headers, but leaves them out from being inserted into the database. Once the while loop begins, the first line has already been returned thus leaving them out of the mysql insert. On top of this it appears the headers were needed and so this solves that as well.
So in the end,
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File " . $_FILES['filename']['name'] . " uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
//Grab the headers before doing insertion
$headers = fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
You can try this:
array_shift($data);
I have implement this code and it is tested code. I think it is very use full
You have follow some rule:-
1.your csv file according to database table name (ex: db table name is users then csv should be users.csv)
2.Your csv file's first row should be db table fields name (ex: Id, name etc) after the start your data entry
3.you can download data source class from :- http://code.google.com/p/php-csv-parser/ because i have require below the code: require_once 'CSV/DataSource.php';
<?php
ini_set('memory_limit','512M');
$dbhost = "localhost";
$dbname = "excel_import";
$dbuser = "root";
$dbpass = "";
$conn=mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());
mysql_select_db($dbname) or die("Unable to select database because: " . mysql_error());
require_once 'CSV/DataSource.php';
$filename = "users.csv";
$ext = explode(".",$filename);
$path = "uploads/".$filename;
$dbtable = $ext[0];
import_csv($dbtable, $path);
function import_csv($dbtable, $csv_file_name_with_path)
{
$csv = new File_CSV_DataSource;
$csv->load($csv_file_name_with_path);
$csvData = $csv->connect();
$res='';
foreach($csvData as $key)
{
$myKey ='';
$myVal='';
foreach($key as $k=>$v)
{
$myKey .=$k.',';
$myVal .="'".$v."',";
}
$myKey = substr($myKey, 0, -1);
$myVal = substr($myVal, 0, -1);
$query="insert into ".$dbtable." ($myKey)values($myVal)";
$res= mysql_query($query);
}
if($res ==1)
{
echo "record successfully Import.";
}else{
echo "record not successfully Import.";
}
}
Declare one variable before while loop
$row=1;
then in while loop put this condition
if($row==1){
$row++;
continue;
}
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File " . $_FILES['filename']['name'] . " uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
fgetcsv($handle); //skip the reading of the first line from the csv file
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}

Convert a csv to mysql through php starting from a particular line?

I have the following code below which works, but I want to insert values to my database from the second row of my csv file. Please any pointers will be great.
$con = #mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
$row = 1;
if (($handle = fopen($csvfile, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
$query = "INSERT into $databasetable(email,emailSource,espBanner,firstName,lastName,Address,City,
State,zip,home,mobile,card,ethnicity,language,gender,filename,is_uploaded)
values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]'
,'$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]',
'$data[14]','$data[15]','$data[16]')";
mysql_query($query) or die(mysql_error());
}
fclose($handle);
}
The result will insert every row of the csv.
$con = #mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
$start_from_row = 2;
$row = 0;
if (($handle = fopen($csvfile, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br></p>\n";
$row++;
if($row < $start_from_row)
continue;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br>\n";
}
$query = "INSERT into $databasetable(email,emailSource,espBanner,firstName,lastName,Address,City,
State,zip,home,mobile,card,ethnicity,language,gender,filename,is_uploaded)
values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]'
,'$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]',
'$data[14]','$data[15]','$data[16]')";
mysql_query($query) or die(mysql_error());
}
fclose($handle);
}

Separate CSV import fields in a query

I would to load a csv into MySQL and manage the single field. the original code uploaded the content with automatic VALUES('','$linemysql');. How can I separate the fields? I would a query like:
$sql = "INSERT IGNORE INTO `database`.`table` (`field1`,field2`, `field3`, `field4`, `field5`) VALUES(`csvfield1`,csvfield2`, `csvfield3`, `csvfield4`, `csvfield5`);";
This because I can manage which row will be included
$lines = 0;
$queries = "";
$linearray = array();
$allLines = split($lineseparator,$csvcontent);
array_shift($allLines); // removes the 1st element
foreach($allLines as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto)
/* Change This query VALUES('','$linemysql'); */
$query = "INSERT IGNORE INTO `database`.`table` (`field1`,field2`, `field3`, `field4`, `field5`) VALUES('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
$queries .= $query . "\n";
Use PHP's built in CSV functionality including fgetcsv(). From the docs:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
You can modify your query like this
$query = "INSERT IGNORE INTO `database`.`table` (`field1`,field2`, `field3`, `field4`, `field5`) VALUES("'.$linemysql[0].'","'.$linemysql[1].'","'.$linemysql[2].'","'.$linemysql[3].'","'.$linemysql[4].'");";
Thanks

Categories