Importing csv into mysql (List of Codes) - php

So I have a list of codes (100,000) to be exact and I got them delivered in a csv file.
I want to put theses codes in a database so I can later get them using my php script.
However my question is how do I get my codes from the file in the right table?
This is what my database looks like at the moment.
The codes from the file need to be inserted in table code.
Hope someone can help me out with this one.

You probably will find this helpful (pls adjust the table and others names):
LOAD DATA INFILE 'codes.csv'
INTO TABLE codes
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
(#id,code,#active)
SET id = null;
SET active = '1'
More details:
http://www.mysqltutorial.org/import-csv-file-mysql-table/

Try this:
you can upload your csv file and post it. then use this function.
this is the PHP code:
function get_csv_file($filename){
if (($handle = fopen($filename, "r")) !== false) {
$filesize = filesize($filename);
$firstRow = true;
$aData = array();
while (($data = fgetcsv($handle, $filesize, ";")) !== false) {
if($firstRow) {
$aData = $data;
$firstRow = false;
} else {
for($i = 0;$i < count($data); $i++) { //only for csv file
if($data[$i] != '')
$aData[] = $data[$i];
}
}
}
//print_r($aData);
fclose($handle);
$finalscrap = array_unique($aData);
// echo "<pre>";
// print_r($finalscrap);
// echo "<pre/>";
return $finalscrap; //this is your record as array format
}
}

Related

Value's not visible when importing CSV after values are added by fputcsv with php

I'm trying to make a translation module for my web project and i hit a wall. I written two functions, one for importing the CSV data and the other for changing, deleting and adding new data to the CSV file.
Everything works like a charm except the adding part. It adds the data to the CSV file but when i want to import it in the website via PHP it doesn't display the added values. (It see that their should be values but it gives empty results in return) the function i use for reading the csv file is:
// Load in CSV (File name, delimiter, Fixed array[key,value] (optional))
function load__CSV($filename='', $delimiter=';', $fixed = null){
if(!file_exists($filename) || !is_readable($filename)) {
return FALSE;
}
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 100000, $delimiter)) !== FALSE) {
if (!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}
fclose($handle);
}
if($fixed != null) {
foreach($data as $entry){
$set_csv[$entry[''.$fixed[0].'']] = $entry[''.$fixed[1].''];
}
} else {
$set_csv = $data;
}
return $set_csv;
}
The function i use to add, edit or remove CSV content is:
// Change csv
function update__csv($csv = 'csv/language.csv',$key = array(2,''),$values = array([3,''],[4,'']),$status = 'change') {
$input = fopen(BASE_URL.$csv, 'r');
$output = fopen(BASE_URL.'csv/temporary.csv', 'w');
while (false !== ($data = fgetcsv($input, 10000, ";"))) {
if ($data[$key[0]] == $key[1]) {
foreach ($values as $value) {
$data[$value[0]] = $value[1];
}
if ($status == 'change' || $status == 'new') {
fputcsv($output, $data, ";");
}
} else {
fputcsv($output, $data, ";");
}
}
if($status == 'new'){
fputcsv($output, $values, ";");
}
fclose( $input );
fclose( $output );
unlink(BASE_URL . $csv);
rename(BASE_URL . 'csv/temporary.csv', BASE_URL . $csv);
}
If i add new values to the CSV file and then open the CSV on my PC and safe it again (without changing a thing) to CSV with UTF-8 encoding then it works as expected and loads the correct data. If i open the CSV in Notepad++ i see this difference between manual added items and php added items:
I tried other encoding methods but that is kinda new for me so i think i did something wrong. Thank you in advance for helping me!
I did find the answer after some more debugging. One value of the array didn't contain a string but a true or false statement. This meant that it didn't add the data the right way into the CSV file.
I fixed it by adding strval() to every variable before putting it into an array.

PHP import CSV file and use data as variables

I would like to import a CSV document and parse its content to use it as variables. The document would always have fixed column names and column numbers. Any examples would be excellent.
I could only find a parse that shows the contents of the CSV file:
<?PHP
/**
* parse-csv.php
*/
$err_upTmpName = 'csvfiletutorial.csv';
$row = 0;
if (($handle = fopen($err_upTmpName, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if($row == 0){
$row++;
} else {
// $data[0] = first name; $data[1] = last name; $data[2] = email; $data[3] = phone
if(!empty($data[0]) && !empty($data[1])) echo $data[0].' - '.$data[1].' - '.$data[2].' -
'.$data[3].' - '.$data[4].'<br/>';
}
}
} else {
echo 'File could not be opened.';
}
fclose($handle);
?>
Input sample csv:
date,value,value2
4.10.2019,15,10
Desired output csv:
using values from CSV file in a formula for example: 15+10
output=
date,sum_values
4.10.2019,25
output gets saved to a new CSV file

How to parse a .csv file into a multidimensional array in PHP?

I'm a newbie in PHP and I'm trying to make a todo list that communicates with a .csv file,. So far I've managed to write a function that writes the user input into the csv file, but I'm stuck on writing a function that would parse (I'm not even sure if this is the correct term) every line of the .csv file into a multi dimensional array, so I could display every line of the list to my convenience in the PHTML file.
Here's what I have so far :
`<?php
//
// ─── DATA ────────────────────────────────────────────────────────────────────
//
$user_entry = array(
'title' => '',
'description' => '',
'date' => '',
'priority' => ''
);
// puts the data the users entered into an array
$user_entry['title'] = $_POST['title'];
$user_entry['description'] = $_POST['description'];
$user_entry['date'] = $_POST['date'];
$user_entry['priority'] = $_POST['priority'];
//
// ─── FUNCTIONS ──────────────────────────────────────────────────────────────────
//
function writeInList() {
//parses the $user_entry array into the .csv file
global $user_entry;
$file = fopen("todo.csv","a");
fputcsv($file, $user_entry, ",");
fclose($file);
}
function displayList() {
//That's where I'm stuck.
$file = fopen("todo.csv","r");
$fileCountable = file("todo.csv");
for ($i = 0; $i < count($fileCountable); $i++) {
$csvContent = fgetcsv($file, 1000, ",");
foreach ($csvContent as $value){
$var[$i] = $value;
}
echo '<br>';
}
fclose($file);
}
//
// ─── MAIN CODE ─────────────────────────────────────────────────────────────
//
writeInList();
include 'todolist.phtml';`
I'm sorry if it has been discussed before. I've searched a lot and found similar questions but can't get to make it work in my own code. Thanks a lot in advance if anyone takes the time to take a look at my code !
This is also my very first time posting here so I hope I'm doing it right.
You did pretty good. You can look at fgetcsv documentation for more. I would have change you function so it will get the argument as input (try avoid using global)
// insert data
function writeInList($user_entry, $path ) {
$file = fopen($path ,"a");
fputcsv($file, $user_entry, ",");
fclose($file);
}
//extract data
function getList($path, $limit = 100000) {
$file = fopen($path, "r");
if (!$file) return null; // or throw error or print to log
$allRows = []; //
while (($data = fgetcsv($file, $limit, ",")) !== FALSE) {
$allRows[] = $data; // as fgetcsv return array already exlode by ","
}
fclose($file);
return $allRows;
}
Now you have 2-Dim array return from getList. Use is as getList("todo.csv") and display as you pleased.
Hope that helps!

PHP use the fputcsv CSV to write same data in column for each row

I am trying to put a new data "exemple" for each line of the CSV. The lines of the csv varies. The header column name would be ExempleRow
There is not separator only a delimiter which is the semi colon.
I'm using fputcsv, it must have an array to fill the csv file with desired data. But in my case the number of lines changes for each csv.
So far it adds the new column with but I can't understand how to put the same value in each line for that column ?
<?php
$newCsvData = array(); // here should I specify the same data value "exemple data" for each line ? but how ?
if (($handle = fopen("exemple.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 9999, ";")) !== FALSE) {
$data[] = 'ExempleRow';
$newCsvData[] = $data;
}
fclose($handle);
}
$handle = fopen('exemple.csv', 'w');
foreach ($newCsvData as $line) {
fputcsv($handle, $line,';',' ');
}
fclose($handle);
?>
If you want to show the keys of the array as the first column then you can do this. If you dont have an associative array or you want to hard code the column headers for what ever reason you can simply change the array_keys($line) for a hard coded array.
$handle = fopen('exemple.csv', 'w');
$keys = false;
foreach ($newCsvData as $line) {
if ($keys === false) {
//$header = array('HeaderOne', 'HeaderTwo', 'HeaderThree', 'HeaderFour'); Use this if you want to hard code your headers
fputcsv($handle, array_keys($line), ';', '');
$keys = true;
}
fputcsv($handle, $line,';',' ');
}
fclose($handle);

nokia csv file import issue in php

Title,"First name","Middle name","Last name","address"
Mr.,"prince","M","Kachhadiya","A-42,AdarshNagar-2
 c.g Road,
"
Address field have value like "A-42,AdarshNagar-2
 ChhpraBhatha Road," this value have comma(,) in between and csv file default field separator is comma(,) so it will assume A-42 and AdarshNagar-2
 c.g Road as different field value.
how can i resolve it?
My Php Code:
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
// Code for parse csv data
}
use fgetcsv() to read from a file . Refer http://www.w3schools.com/php/func_filesystem_fgetcsv.asp
Title,"First name","Middle name","Last name","address"
Mr.,"prince","M","Kachhadiya","A-42,AdarshNagar-2 c.g Road,"
//You can't split the strings using CSV functions so better do some manual work
//All csv values are quoted with double quotes so split the string like this
//**If file size is minimum use this function**
$data = file_get_contents('<file_path>');
$parsed_string = explode('",', $data);
$cnt = count($parsed_string);
for($i=0; $i<$cnt; $i++)
{
$value = substr($parsed_string,1);
}
//**If file size is maximum use this**
$file = fopen("<file path>","r");
while(! feof($file))
{
$data = fgets($file);
$parsed_string = explode('",', $data);
$cnt = count($parsed_string);
for($i=0; $i<$cnt; $i++)
{
$value = substr($parsed_string,1);
}
}
fclose($file);

Categories