While uploading csv file in mysql using php - php

While I am uploading a csv file using php coding in MySQL ,all rows and columns were inserting .I have 670 data in it but it is inserting 1000 rows,I want only 670 rows to be added

Please check below code hope this help you
$count=0;
while(($data = fgetcsv($inputfp, 4096, ',')) !== FALSE) {
if($count==670) Break;
else{
//your inserting code here
}
$count++;
}

Related

Populating mysql database with csv file using php

I'm trying to populate a mysql database with the contents of a .csv file using php. I'd like to do it using php code (no phpadmin). I consulted another thread on stackoverflow (populating database from csv file using php) but am still getting stuck. Here is my code:
$file = fopen("input.csv", "r");
while ($data = fgetcsv($file, $lineLength = 0, $delimiter = ",")) {
$added = "INSERT INTO Items VALUES(".$data.")";
if($connection->query($added) === TRUE) {
echo "Values successfully added!";
} else {
echo "Error inserting values: " . $connection->error;
}
Some context: earlier in the code, I create a database, connect to it, and create a table in the database. That part works fine. I just get an error when I try to populate the database from a .csv file. Here is the error message I get:
Notice: Array to string conversion in C:\xampp\htdocs\assignment8\init.php on line 64
Error inserting values: Unknown column 'Array' in 'field list'
I get this message 12 times, which corresponds with the number of rows in the .csv file I'm trying to import. "Line 64" corresponds with the line in my code that starts with "$added = INSERT INTO..."
Any help or suggestions are greatly appreciated.
You have to access to your column in the array
If your csv is something like this
Inside your while, you can access the values like:
echo $data[0] // prints 'Value 1'
So you might want to do something like...
$added = "INSERT INTO Items VALUES(".$data[0].")";

Parsing Excel data from specific row and columns to MySQL using PHP

currently im doing my homework project to parse specific data from excel to MySQL using PHP. The project is about uploading an excel file and then the excel data supposed to be in MySQL after excel file uploaded.
The problem that im facing is, my homework project requirement is only parse specific row and column amongst the data exists in the excel file. I have already try using codes that i found, but it doesn't work. It parse everything in the excel files to MySQL table. Not the specific Row and Columns data that i expected.
I'm still looking for a solution for this. Spent almost 2 weeks for this but still i'm facing a dead end. My deadline project in 1 week. So, i would be really thankful if someone could help me and get me a solution of this.
I have tried on this PHP script. But, all the data in excel were parsed to MySQL table and the data messed the row and column in MySQL table. I want only the specific part (row and column) of excel files to be inserted to MySQL table that i've crated. i provided screenshot and the part that i want to be parsed to MySQL table highlighted with red color.
if(!empty($_FILES['excelfile']['name'])){
// Get File extension eg. 'xlsx' to check file is excel sheet
$pathinfo = pathinfo($_FILES['excelfile']['name']);
// check file has extension xlsx, xls and also check
// file is not empty
if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
&& $_FILES['excelfile']['size'] > 0 ){
$file = $_FILES['excelfile']['tmp_name'];
$reader = ReaderFactory::create(Type::XLSX);
$reader->open($file);
$count = 0;
foreach ($reader->getSheetIterator() as $sheet){
foreach($sheet->getRowIterator () as $row)
{
if ($count > 0){
$name = $row[2];
$job_schedule = $row[3];
$overtime = $row[4];
$notes = $row[5];
$start_working = $row[6];
$finished_working = $row[7];
$qry = "INSERT INTO `timesheet` (`name`,`job_schedule`, `overtime`,`notes`, `start_working`,`finished_working`) VALUES ('$name','$job_schedule','$overtime','$notes','$start_working','$finished_working')";
$res = mysqli_query($con,$qry);
}
$count++;
}
}
if($res){
echo "Success";
}
else{
echo "failed";
}
$reader->close();
}
else{
echo "Excel format is not supported";
}
```[Here is the SCREENSHOT LINK]
[1]: https://i.stack.imgur.com/0kIxo.png
You can follow this link:
Exporting data from php to excel
I recommend use PHPExcel php class, just plug and play, I've done it myself. It's works better than trying to figure everthing by yourself.

Read a CSV file and upload data to correct table in PHP

I have a SQL database with 5 tables and I also have 5 CSV files, one for each of those tables.
I am struggling to create a PHP script that can be used to read each files and then upload the data into the correct table.
How can I go about this?
URL - http://php.net/manual/en/function.fgetcsv.php
<?php
$filename = "test.csv";
//Open the csv file in the read mode
if (($handle = fopen($filename, "r")) !== FALSE) {
//loop into the each row and do the stuff
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//$data will have all the related columns
//Make sure you will use INSERT query here
}
fclose($handle);
}
If you want to write to specific tables there are many way to do so
Create 5 files where in each and every file while loop you will have that respective table name.
Eg : Think that you want to insert for customers.csv file
Then in while loop you may use the following way
while(/*Code*/){
//INSERT INTO customers (col1, col2) VALUES (val1, val2);
}
In case if your lazy than in one file only you can make a switch operation as follows
$filename = 'customers.csv';
switch( $filename ) {
case 'customers.csv':
while(){
//Insert
}
break;
case 'products.csv':
while(){
//Insert
}
break;
}

PHP - insert into mutiple tables, each table with identifcal fields

I'm going to explain with my best efforts what my goal is here. Everything I've searched for online hasn't been relevant enough for me to gain an idea.
First off, this is a PHP assignment where we have to load CSV files into a MySQL database.
Now, each table (total of 4) have the exact same field values. What I am trying to accomplish is using a for each loop that populates each table with the information from the CSV file. I know I can do this by having a while loop for each table and CSV file but I'm trying to go above the requirements and learn more about PHP. Here is my code for what I'm trying to accomplish:
$files = glob('*.txt'); // .txt required extension
foreach($files as $file) {
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle,4048, ",")) !== FALSE) {
echo $data[0]; // making sure data is correct
$import = "INSERT INTO".basename($file)."(id,itemName,price) VALUES('$data[0]','$data[1]','$data[2]')";
multi_query($import) or die (mysql_error());
}
fclose($handle);
}
else {
echo "Could not open file: " . $file;
}
}
Each CSV file contains the id, itemName and price. Hopefully this is understandable enough. Thank you
The way you are importing data into MySQL is OK for small volume of data. However, if you are importing huge volumes(thousands of rows), the best way would be to import it directy into MySQL is by using infile. Fo example:
LOAD DATA LOCAL INFILE '/path/to/your_file.csv'
INTO TABLE your_table_name
FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES
TERMINATED BY '\n' (id, itemName, price)
That's a smarter way to import your CSV data :)

csv file upload in php inserts only first row in database

I want to upload csv file in mysql database in php. I am using,
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle,1000,',','"')) !== FALSE) {
// insert into database...
}
fclose($handle);
But, it inserts only first row of the file.
EDIT:
when I am trying to print_r $data within while loop, then also it's giving me only one row.

Categories