Insert values from csv file to MySQL table - php

I'm trying to insert values extracted from a csv file to a mysql table. It runs but the table is not populated. I've tried to debug for the last XXXX but just can't see my error. Echo-ing out the values give me the correct SQL but when it comes to the INSERT - no dice.
Thanks very much for your help.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
//////////////////////////////// EDIT ////////////////////////////////////
$redirect_num = 500; // Select how many rows to insert each time before refresh.
// More rows = faster insertion. However cannot be too high otherwise it will timeout.
$filename = "ps4_emails.csv"; // The file we are going to get the data from...
$table = "`ps4_emails`";
////////////////////////////// END EDIT //////////////////////////////////
$file = file($filename);
$lines = count($file);
// Have we just redirected?
$nextline = $_GET['nextline'];
if (!isset($nextline)){
$nextline = 0;
}
$query = "INSERT INTO ".$table." (email) VALUES ('".$final_line[0]."')";
for ($line=$nextline; $line<=$lines; $line++){
$final_line = explode(",", $file[$line]);
if ($line!=$lines){
mysql_query($query,$db);
}
if ($line % $redirect_num){
// something needs to go here
} else {
$nextline = $line+1;
exit ('<meta http-equiv="refresh" content="0;url=texttomysqlemails.php?nextline='.$nextline.'" />');
}
echo ( $line==$lines ) ? "Done" : "";
}
?>

Put your query inside loop in order use it with variable $final_line.
Try this :
$final_line = explode(",", $file[$line]);
if ($line!=$lines){
$query = "INSERT INTO ".$table." (email) VALUES ('".$final_line[0]."')";
mysql_query($query,$db);
}
Don't use mysql_*. It's deprecated and removed from PHP 7. Use mysqli_* or PDO.

This seems like a perfect script to run from the command line PHP CLI and therefore you can forget about all the refresh complexity.
If the file is huge, like your comment suggest, loading all the file into memory may also bring you up against the PHP memory limits, so it might be better to read a line at a time rather than the whole file using fgetcsv() which is intended for reading csv files.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
$filename = "ps4_emails.csv";
$table = "";
$handle = fopen('ps4_emails.csv', 'r');
if ( ! $handle ) {
echo 'File does not exists in this location';
exit;
}
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$query = "INSERT INTO `ps4_emails` (email) VALUES( '{$data[0]}')";
mysql_query($query,$db);
}
?>
You now just run this script from the command line/terminal like
>php script.php
And it can run for minutes/hours/days with no likleyhood of blowing any limits.
I have to mention this or someone will nag me for not saying it
Please dont use the mysql_ database extension, it is deprecated (gone for ever in PHP7)
Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions,
and here is some help to decide which to use
When you need to upload the real file, it would also be a good idea to add a restart mechanism, so you can restart the process from whereever a problem happened or someone shut the database down for a backup or some other unforseen hiccup.
<?php
$host = 'localhost';
$user = 'fulltime_admin';
$pass = 'secret';
$database = 'fulltime_db';
$restart_from = 0;
$db = mysql_connect($host, $user, $pass);
mysql_query($database, $db);
$filename = "ps4_emails.csv";
$table = "";
$handle = fopen('ps4_emails.csv', 'r');
if ( ! $handle ) {
echo 'File does not exists in this location';
exit;
}
// is it a restart?
if ( file_exists('restart.txt') ) {
// its a restart
$restart_from = file_get_contents('restart.txt');
// read up the file to the last good row inserted
for ( $i=0; $i<=$restart_from; $i++ ) {
$data = fget($handle, 1000);
}
}
$upd_cnt = restart_from;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$query = "INSERT INTO `ps4_emails` (email) VALUES( '{$data[0]}')";
mysql_query($query,$db);
$upd_cnt++;
file_put_contents('restart.txt', $upd_cnt);
}
?>
The above restart code is not tested, but I have used something very like this in the past very successfully. So you will have to check I have not made any silly mistakes, but it should give you an idea of how to do a restart from the last row successfully updated before a crash.

You can use LOAD DATA INFILE to insert from file.
refer http://dev.mysql.com/doc/refman/5.7/en/load-data.html
insert csv file data into mysql

Related

PHP PDO MySQL: Insert statement runs without error, no insert occurs

My code:
<?php
try {
$t = '040485c4-2eba-11e9-8e3c-0231844357e8';
if (array_key_exists('t', $_REQUEST)) {
$t = $_REQUEST["t"];
}
if (!isset($_COOKIE['writer'])) {
header("Location: xxx");
return 0;
}
$writer = $_COOKIE['writer'];
$dbhost = $_SERVER['RDS_HOSTNAME'];
$dbport = $_SERVER['RDS_PORT'];
$dbname = $_SERVER['RDS_DB_NAME'];
$charset = 'utf8' ;
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->prepare("select writer from mydbtbl where writer=? and t=?");
$stmt->execute(array($writer, $t));
$num = $stmt->fetch(PDO::FETCH_NUM);
if ($num < 1) {
header("Location: login.php");
return 0;
}
$dbMsg = "Authorized";
$dbname = 'imgs';
$dsn = "mysql:host={$dbhost};port={$dbport};dbname={$dbname};charset={$charset}";
$pdo = new PDO($dsn, $username, $password);
if (isset($_FILES['filename'])) {
$name = $_FILES['filename']['name'];
// set path of uploaded file
$path = "./".basename($_FILES['filename']['name']);
// move file to current directory
move_uploaded_file($_FILES['filename']['tmp_name'], $path);
// get file contents
$data = file_get_contents($path, NULL, NULL, 0, 60000);
$stmt = $pdo->prepare("INSERT INTO file (contents, filename, t) values (?,?,?)");
$stmt->execute(array
($data,
$name,
$t)
);
$dbMsg = "Added the file to the repository";
// delete the file
unlink($path);
}
} catch (Exception $e) {
$dbMsg = "exception: " . $e->getMessage();
}
In the code you will see that the first part is for doing authentication. Then I create a new PDO object on the img schema, and do my file insert query after that.
Later, where I am printing out $dbMsg, it is saying "added file to the repository". But when I query the database (MySQL on Amazon AWS using MySQL Workbench) nothing has been inserted.
I don't understand why if nothing is getting inserted I am not getting an error message. If it says "added file to the respository", doesn't that mean the insert was successful? The only thing I can think is that using a different schema for this is mucking things up. All of my inserts to ebdb are going through fine
--- EDIT ---
This question was marked as a possible duplicate on my query about not getting an error message on my insert / execute code. This was a useful link and definitely something I will be aware of and check in the future, but ultimately the answer is the one I have provided regarding the terms of service for my aws account
The answer is that the (free) amazon account policy I am working under only allows me to have 1 database / schema. When I switched the table over to ebdb it worked right away. I am answering my own question (rather than deleting) so hopefully others using AWS / MySQL can learn from my experience.

How to bypass maximum execution time in php?

I know this is an ugly idea, but how can I bypass this maximum execution error. I don't want to configure any .ini that I have read in some solutions.
I have this code to upload csv to sql database but this keeps me giving an error when uploading large files. Please help me revise my code guys
<?php
if(isset($_POST['submit'])) {
$host = 'localhost';
$user = 'root';
$password = '';
$db = 'jeremy_db';
$con = mysqli_connect($host,$user,$password) or die('Could not' .mysqli_error($con));
mysqli_select_db($con, $db) or die ('Could not' .mysqli_error($con));
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
while(($csvdata = fgetcsv($handle,10000,","))!== FALSE){
$sha1 = $csvdata[0];
$vsdt = $csvdata[1];
$trendx = $csvdata[2];
$sql = "INSERT INTO jeremy_table_trend (sha1,vsdt,trendx) VALUES ('$sha1','$vsdt','$trendx')";
$query = mysqli_query($con , $sql);
$c = $c+1;
}
if($query){
echo "success";
}
else {
echo "error";
}
}
?>
try this
add this line to your code
ini_set('max_execution_time', 300); //300 seconds = 5 minutes //whatever you want
Taken from How to increase maximum execution time in php
Executing insert statements in the loop is expensive. You can try dumping the csv file directly into MySQL, that will take relatively lesser execution time.
Refer to this question

TXT to SQL that automatically removes that line of txt once complete

I have a wordpress plugin that exports form entries to a txt file. So I need to write a php script to add them to a sql database as I want the submissions added to a database on a different domain (otherwise I’d just get the plugin to do it for me). I’m fine about how I get it to connect to the database, it’s just how I code it to interpret the data as the column names are always next to the field as shown.
{"Entry_ID":"235","Name":"matt","Email":"matt#gmail.com","Date":"03/10/2017"}{"Entry_ID":"236","Name":"matt","Email":"matt#btinternet.com","Date":"10/10/2017"}
Is there a way to get it to ignore the column name and only interpret the data within the “” after the : ?
Once these have been added to the sql database I would then need to get the lines removed from the txt
So far I have this but it isn't working...
$file= fopen('http://mpcreations.staging.wpengine.com/wp-content/themes/red-seal-resources/test.txt', 'r');
while (($data = fgetcsv($file)) !== FALSE) {
$object = json_encode($data[0]);
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "INSERT INTO 'wp_forms' LINES TERMINATED BY '\n';
if (mysqli_multi_query($conn, $query)) {
echo "New records created successfully";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
Any help would be greatly appreciated.
Thank you
Each line in the txt file has JSON data? Process the txt file, parse the data and INSERT it into the database table.
$file= fopen('file.txt', 'r');
while (($data = fgetcsv($file)) !== FALSE) {
$object = json_encode($data[0]);
// Prepare INSERT query here...
}

CSV INPUT from front end using PHP MySQL [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I want to insert data to phymyadmin table using CSV file from front-end of website, which must UPDATE all the record previously in my table.
This code isn't working at all. Please locate the error.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = mysql_connect($servername, $username , $password );
if(! $conn ) {
die('Could not Find Some Error Occured: ' . mysql_error());
}
if(isset($_POST["submit"]))
{
if($_FILES['file']['name'])
{
$filename = explode(".", $_FILES['file']['name']);
if($filename[1] == 'csv')
{
$handle = fopen($_FILES['file']['tmp_name'], "r");
while($data = fgetcsv($handle))
{
$uname = mysqli_real_escape_string($connect, $data[0]);
$pass = mysqli_real_escape_string($connect, $data[1]);
mysql_select_db('desiresq_record');
$query = "INSERT into login (username, password)
VALUES ('$uname','$pass')";
mysqli_query($connect, $query);
}
fclose($handle);
echo "<script>alert('Import done');</script>";
}
}
}
?>
You're using both MySQL and the MySQLi extensions in your script.
I'd suggest just sticking to MySQLi, seeing as MySQL is long deprecated and shouldn't be used due to security issues.
Best of luck!

Can't connect to my database with php PDO

I'm trying to make a function for a website where after you log in to, you can upload a csv file to the database into table csv. But when i try to upload the csv file it gives me the following error;
SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'server2.bhosted.nl' (111)
The code that i use is this ->
<?php
session_start();
// mysql hostname
$hostname = 'server2.bhosted.nl';
// mysql username
$username = 'username';
// mysql password
$password = 'password';
// databasename
$dbname = 'birdss';
// Get Extension of the File.
$extension= end(explode(".", basename($_FILES['file']['name'])));
// isset Determines if a variable is set and is not NULL. Set Size Limit less then 10 MB=10485760 bytes. Extension must be CSV.
if (isset($_FILES['file']) && $_FILES['file']['size'] < 10485760 && $extension== 'csv')
{
// We will get csv file and save it in a $file
$file = $_FILES['file']['tmp_name'];
//$handle is a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen(). fopen() used to open file.
$handle = fopen($file, "r");
// We will use try{} Catch() statements here.
try {
// Database Connection using PDO
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname;", $username, $password);
// Truncate Table before insertion
$STMR = $dbh->prepare("TRUNCATE TABLE csv");
$STMR->execute();
// Prepare the statement for the insertion in the table
$STM = $dbh->prepare('INSERT INTO csv (tijd, aantal) VALUES ("'.$data['tijd'].'", "'.$data['aantal'].'")');
//Check handel is True or False
if ($handle !== FALSE)
{
// fgets() Gets a line from file pointer and read the first line from $handle and ignore it.
fgets($handle);
// While loop used here and fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
{
// For Executing prepared statement we will use below function
$STM->execute($data);
}
//The file pointed to by handle will be closed.
fclose($handle);
// Closing MySQL database connection
$dbh = null;
// If data inserted successfully we will redirect this page to index.php and show success message there with code 77083368
header( "location:index.php?ServerStatsAdded=77083368");
}
}
//
catch(PDOException $e)
{
die($e->getMessage());
}
}
else
{
// Error mesage id File type is not CSV or File Size is greater then 10MB.
header( "location:index.php?ServerStatsAdded=37767");
}
?>
Please help me!!
Try this way by removing second ; after $dbname variable but check your credentials again.
$hostname = 'server2.bhosted.nl';
$username = 'username';
$password = 'password';
$dbname = 'birdss';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
EDIT:
As error (111) means only listen on localhost, If you have lines like this :
skip-networking
bind-address = 127.0.0.1
In your my.cnf configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.

Categories