Save CSV files into mysql database - php

I have a lot of csv files in a directory. With these files, I have to write a script that put their content in the right fields and tables of my database. I am almost beginner in php language : I have found some bits of code on the Internet. It seems to work, but I am stuck at a stage. Some topics are related on this website, but I did not found the ecat problem.
I have written a php script that permits to get the path and the name of these files. I managed too to create a table whose name depends of each csv (e.g : file ‘data_1.csv’ gives the table data_1.csv in my-sql). All the tables have the three same fields, id, url, value.
The last thing to do is to populate these tables, by reading each file and put the values separated by ‘|’ character in the right tables. For example, if a line of ‘data_1.csv’ is
8756|htttp://example.com|something written
I would like to get a record in data_1.csv table where 8756 is in id, htttp://example.com in url field, and something written in value field.
I have found the way to read and print these csv with fcsvget function. But I do not know how to make these lines go into the SQL database. Could anyone help me on this point?
Here is my script below
<?php
ini_set('max_execution_time', 300);
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, true) or die ('Error connecting to mysql');
$dbname = 'test_database';
mysql_select_db($dbname);
$bdd = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else {
echo "hello <br>";
}
$dir = 'C:\wamp\www\test';
$imgs = array();
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!is_dir($file) && preg_match("/\.(csv)$/", $file)) {
array_push($imgs, $file);
}
}
closedir($dh);
} else {
die('cannot open ' . $dir);
}
foreach ($imgs as $idx=>$img) {
$class = ($idx == count($imgs) - 1 ? ' class="last"' : '');
$filePath=$dir . '\\'. $img;
$file = fopen($filePath, "r") or exit("Unable to open file!");
$nom = 'FILE: ' . $dir . '\\'. $img;
echo $nom;
settype($nom, "string");
echo '<br>';
$chemin = '<img src="' . $dir . $img . '" alt="' .
$img . '"' . $class . ' />' . "\n";
echo $chemin;
$file_name = basename($filePath);
$sql = 'CREATE TABLE `' . $file_name . '` (id int(20000), url varchar(15), value TEXT)';
mysql_query($sql,$conn);
$handle = fopen($filePath, 'r');
while (($row = fgetcsv($handle)) !== false) {
foreach ($row as $field) {
echo $field . '<br />';
}
}
fclose($handle);
}
echo ("VERIFY");
for ($i = 1; $i <= 1682; $i++) {
echo ("<br>A : " . $i);
$checkRequest= "select * from movies where movieID='". $i."'";
echo ("<br>". $checkRequest);
if ($result = $mysqli->query($checkRequest)) {
printf("<br> Select ". $i ."returned %d rows.\n", $result->num_rows);
if ($result->num_rows == 0) {
echo ("I : " . $i);
}
$result->close();
}
}
$mysqli->close();
?>

MySQL provides a wonderful feature that allows you to import a CSV file directly, in a single query.
The SQL command you're looking for is LOAD DATA INFILE
Manual page here: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Quick example:
LOAD DATA INFILE 'fileName'
INTO TABLE tableName
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(
field1,
field2,
field3,
#variable1,
#variable2,
etc
)
set
(
field4 = concat(#variable1,#variable2)
);
That's a fairly basic example, but it covers most of what you'd want. The manual page gives full details of how to do some very complex stuff with it.
Hope that helps.

after
foreach ($row as $field) {
echo $field . '<br />';
You need to parse the result after ; like:
$pieces = explode(";", $field);
and then insert every piece into the database
$sql = ' INSERT INTO X VALUES ("'.$pieces[0].'","'.$pieces[1].'","'.$pieces[2].'","'.$pieces[3].'","'.$pieces[4].'")';
mysql_query($sql, $conn);

Also mysqlimport can be used
private function runImport($host, $username, $password, $schema, $csvFilePath) {
$output = array();
$cmd = "/usr/bin/mysqlimport --host=$host";
$cmd .= ' --fields-terminated-by=\',\' --fields-optionally-enclosed-by=\'"\' ';
$cmd .= ' --user=' . $username . ' --password='. $password;
$cmd .= " $schema $csvFilePath";
exec($cmd, $output, $retVal);
foreach ($output as $line) {
echo "$line\n";
}
echo "\n\nReturn code : $retVal";
}

Related

importing an .sql.gz file into mysql using php

I am currently working on an script that will easily import an backup in 2 clicks, but i can't find any information on how to import and .gz file.
and .sql file works great but if im going to decompress it i can just aswell just import it using phpmyadmin.
when i currently try to import the .gz file i just get one massive error of unreadable characters.
How can i make it so i can import an .gz file
The point here is that it is an WEB based importer
$userName = "root";
$password = "";
$dbName = "test";
$conn = #new mysqli($serverName,$userName,$password,$dbName);
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: " . $con->connect_errno;
echo "<br/>Error: " . $con->connect_error;}
$fileName = "189_dump.sql.gz";
$temp = "";
$lines = file($fileName);
foreach($lines as $line){
if(substr($line, 0, 2) == '--' || $line == '')
continue;
$temp .= $line;
if(substr(trim($line), -1, 1) == ';'){
$conn->query($temp) or print('Error performing query \'<strong>' . $temp . '\': '. '<br /><br />');
$temp = "";
}
}
echo "imported db (or not)";
?>
This is how i fixed it:
$lines = gzfile($fileName);
<?php
class reader{
public $dbName;
public $fileName;
public function import($dbName, $fileName){
$serverName = "localhost";
$userName = "root";
$password = "";
$conn = new mysqli($serverName,$userName,$password,$dbName);
$temp = "";
$lines = gzfile($fileName);
foreach($lines as $key => $line ){
if(substr($line, 0, 2) == '--' || $line == '') continue;
$temp .= $line;
if(substr(trim($line), -1, 1) == ';'){
$conn->query($temp) or print('Error performing query \'<strong>' . $temp . '\': '. '<br /><br />');
$temp = "";}
}
echo "<script>alert('Database Imported')</script>";
}
}
$bestand = new reader();
# dbname | file name
$bestand->import("test", "testdb.sql.gz");
?>
If you have system() allowed you can:
<?php
system("gzip -dc < ".$file." | mysql -u $dbuser -p$dbpassword $dbname");

PHP import CSV from server to SQL database

I haven't found anything useful about my problem on google or on here.
Currently, I'm storing a CSV file from an URL to my server using cronjob and file_get_contents(); once per hour.
Right now there are several steps executed whenever a user loads the page, but it's all PHP and Javascript from there so it takes about 9 second to load the page with the end result (html table) as described here.
I want to change that by importing the CSV file stored on my server to a SQL database but I have no idea how to realise this. Tried converting it to an array with PHP and then storing it to a db like here, but it didn't work for me. How would you approach this problem?
Thanks, Innerwolf.
file looks like:
username,score,numWins,numKills,numKillsWallshot,numDeaths,numShots,highestSpree,timePlayed
/\ssa,14104,26,2113,0,867,28083,15,43695
"∀ЈAIIX",10166,18,2641,0,1291,34201,14,59346
i tried this new cron
<?php
function download_remote_file($file_url, $save_to)
{
$content = file_get_contents($file_url);
file_put_contents($save_to, $content);
}
download_remote_file(//link', realpath(".//path") . '/dump.csv');
if(!function_exists('str_getcsv')) { ------|
//define str_getcsv |until now, cron
} |job executes
} |part above.
$url = '//path/dump.csv'; |
$csvData = file_get_contents($url); |this part was in
$lines = explode(PHP_EOL, $csvData); |index.htm before
$array = array(); |and gets exe-
foreach ($lines as $line) { |cuted when
$line = str_replace("\\", "\", $line); |reload
$line = str_replace("#", "#", $line); |
$array[] = str_getcsv($line); |
} ------|
$fields = implode(', ', array_shift($array));
$values = array();
foreach ($array as $rowValues) {
foreach ($rowValues as $key => $rowValue) {
$rowValues[$key] = mysql_real_escape_string($rowValues[$key]);
}
$values[] = "(" . implode(', ', $rowValues) . ")";
}
//mySQL connection values
// Create connection
$conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "INSERT INTO ranking ($fields) VALUES " . implode (', ', $values);
if ($conn->query($query) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
$conn->close();
?>

php generating csv file only works first time

I've the following script:
<?php
//Define basepath for codeigniter
define('BASEPATH', '/');
//Include constants.php config file from codeigniter
require_once "../../my_manager/system/application/config/constants.php";
//Check username and password from GET
if( $_GET['username'] != IMPORT_USERNAME || $_GET['password'] != IMPORT_PASSWORD )
{
header('HTTP/1.0 401 Unauthorized');
echo "Denied Access";
return;
}
//running scripts
include 'export_table1.php';
include 'export_table2.php';
include 'export_table3.php';
include 'export_table4.php';
?>
Eache export is like the following:
<?php
//$host="localhost";
$host="";
$user="";
$pass="";
$db_name="";
$table="table1";
$conn = mysqli_connect($host,$user,$pass,$db_name) or die("Connection Error");
$query = "SELECT * FROM $table ORDER BY ID";
$result = mysqli_query($conn,$query) or die("sql error");
if(mysqli_num_rows($result)>0)
{
$csv = "";
$row = mysqli_fetch_assoc($result);
$delim = "";
//retrieving first line fields
foreach($row as $k => $v)
{
$csv .= $delim . '"' . str_replace('"', '""', $k) . '"';
$delim= ";";
}
$csv .= "\n";
//retrieving value into fields
while($row = mysqli_fetch_assoc($result))
{
$delim = "";
foreach($row as $v)
{
$csv .= $delim . '"' . str_replace('"', '""', $v) . '"';
$delim = ";";
}
$csv .= "\n";
}
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=".$table.".csv");
echo $csv;
exit
}
else
{
echo "No records";
}
exit
?>
The issue is that only the first script is fired, so I can get only the first table downloaded into csv file. If I launch first the table2 export, only table2 export is fired. How can I manage that? Thanks in advance!
As far as i know "exit" kills both child- and parent-script - that's the cause why you only get the first table exported in a csv. Use "return" instead to continue.

Php script to export mysql table data to a csv, escaping data from certain columns and mapping strings to arrays?

I need to migrate data within our old bug tracker (Zentrack) to our new one and the only import method I can use is to import from CSV. To do so I need the data from two tables, tickets and logs so I wrote the script below in php.
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "dbuser";
$pass = "dbpass";
$db = "zentrk";
$users[1] = 'john';
$users[4] = 'sally';
$users[5] = 'nick';
$users[6] = 'ralph';
$r = mysql_connect($host, $user, $pass);
if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
echo mysql_get_server_info() . "\n";
$r2 = mysql_select_db($db);
if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
$query_tickets = "select ZENTRACK_TICKETS.id, ZENTRACK_TICKETS.title, ZENTRACK_TICKETS.priority, ZENTRACK_TICKETS.status, ZENTRACK_TICKETS.description, ZENTRACK_TICKETS.otime,
ZENTRACK_TICKETS.type_id, ZENTRACK_TICKETS.user_id, ZENTRACK_TICKETS.system_id, ZENTRACK_TICKETS.creator_id, ZENTRACK_TICKETS.proj_key
from ZENTRACK_TICKETS
where ZENTRACK_TICKETS.status = 'OPEN'
and ZENTRACK_TICKETS.system_id in ('18', '3', '6', '1', '16', '7', '9', '4', '20')
and ZENTRACK_TICKETS.type_id not in ('1', '10', '5')";
$rs = mysql_query($query_tickets);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}
$export = array();
$export[] = 'id,title,created date,priority,type,assigned,description,system,creator,project key,log1,log2,log3,log4,log5,log6,log7,log8,log9,log10
';
while ($row = mysql_fetch_assoc($rs)) {
$line = '';
$count = 0;
$line .= $row['id'] . "," . $row['title'] . "," . date('d-M-y h:m a',$row['otime']) . "," . $row['priority'] . "," . $row['type_id'] . "," . $row['user_id'] . "," . $row['description'] . "," . $row['system_id'] . "," . $row['creator_id'] . "," . $row['proj_key'] . ",";
$logs = find_logs($id = $row['id']);
foreach($logs as $log_entry) {
$line .= $log_entry.",";
$count++;
}
while($count < 10) {
$line .= ",";
$count++;
}
$export[] = $line.'
';
}
mysql_close();
// print_r($export);
$file = 'tickets.csv';
file_put_contents($file, $export);
function find_logs($ticket) {
$content = array();
$query = "select ZENTRACK_LOGS.created, ZENTRACK_LOGS.user_id, ZENTRACK_LOGS.entry
from ZENTRACK_LOGS
where ZENTRACK_LOGS.ticket_id = $ticket
and ZENTRACK_LOGS.action <> 'EDIT' ";
$rs = mysql_query($query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
}
while ($row = mysql_fetch_assoc($rs)) {
$date = date('d-M-y h:m a',$row['created']);
$content[] = $date . ";" . $row['user_id'] . ";" . $row['entry'];
}
return $content;
}
?>
I'm running into two problems with this script, that I'm sure are due to me being new to PHP.
1) I need to escape out the data in $row['description'] as it contains both carriage returns and , in the text that is incorrectly breaking the output into new rows when saved to CSV. I need to save the contents of this row within " " but I'm not sure how to do so.
2) The data returned in $row['user_id'], $row['creator_id'] and $row['user_id'] within the find_logs function returns a number, which I need to find that number and replace with the corresponding string in the $users array. What's the best way to do this?
When dealing with csv files use fgetcsv and fputcsv, provide it with an array and it will handle the escaping for you.

PHP export to Excel file gives me source code in columns

I feel like I'm making a simple mistake but I can't seem to figure out what.
I have some code for exporting a mySQL table to an Excel file.
However, when I do the export, the entire HTML source code gets exported along with my data. I open the file in Excel and my table data in there but it's also got all the HTML inside.
What could be causing all the source code to be exported along with the data?
I should mention that I'm using this code as part of a Wordpress plugin I'm writing. When I test the export outside wordpress, it works fine. But when I try to export from a Wordpress admin page, I get all the extra HTML source code.
Try this code.
$host = 'localhost';
$user = 'mysqlUser';
$pass = 'myUserPass';
$db = 'myDatabase';
$table = 'products_info';
$file = 'export';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$res = mysql_query("SELECT * FROM $table");
// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
// remove the result pointer back to the start
mysql_data_seek($res, 0);
// and loop through the actual data
while($row = mysql_fetch_assoc($res)) {
$line = "";
$comma = "";
foreach($row as $value) {
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
}
fclose($fp);
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv');
Thanks,
Kanji

Categories