PHP csv upload works on mac but not windows - php

I have a csv upload plugin for wordpress. I can upload the files on a mac but on a windows pc it fails to upload. The csv files are created on the pc with utf-8 encoding.
if (isset($_POST) && !empty($_POST)) {
if (isset($_FILES) && $_FILES['csv_file']['size'] > 0 && $_FILES['csv_file']['type'] === 'text/csv') {
global $wpdb;
ini_set("auto_detect_line_endings", true);
$start_row = (int) $_POST['start_row'];
/*
* Get CSV data and put it into an array
*/
$fileData = file_get_contents($_FILES['csv_file']['tmp_name']);
$lines = explode(PHP_EOL, $fileData);
$csv = array();
foreach ($lines as $line) {
$csv[] = str_getcsv($line);
}
/*
* Put each row into the database
*/
$x = 1;
$insert_count = 0;
$insert_output = array();
$wpdb->query('TRUNCATE TABLE table');
foreach ($csv as $data) {
if ($x >= $start_row) {
$date = fix_date($data[0]);
$sql = "
INSERT INTO table ( date, column_1, column_2, column_3, column_4, column_5, column_6, column_7 )
VALUES ( '" . $date . "', '" . addslashes( $data[1] ) . "', '" . utf8_encode( $data[2] ) . "', '" . addslashes( $data[3]) . "', '" . $data[4] . "', '" . addslashes( $data[5] ) . "', '" . $data[6] . "', '" . $data[7] . "' )
";
$wpdb->query($sql)/* or die($sql)*/;
$insert_output[] = $insert_count . '. Added: ' . $data[1] . ' - ' . $data[3] . '<br />';
$insert_count++;
}
$x++;
}
echo '<div class="csv_success">Success. ' . number_format($insert_count) . ' rows uploaded.</div>';
} else {
echo '<div class="csv_failure">Please make sure the file you uploaded is a CSV.</div>';
}
}
Any ideas how I can get this to work on windows and mac?
Cheers

<?php
ini_set('max_execution_time', 0);
$con = mysql_connect("localhost", "", "") or die("not connect");
mysql_select_db("demo") or die("select db");
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
//Set path to CSV file
$csvFile = 'page.csv';
$csv = readCSV($csvFile);
//echo count($csv);
for ($i=1; $i <count($csv) ; $i++) {
$sql="insert into demo1 (name,bdate,phonenumber ) values('".$csv[$i][0]."','".$csv[$i][1]."' ,'".$csv[$i][2]."')";
mysql_query($sql);
}
echo 'done';
?>

Related

only one row importing from csv to mysql table in php

I am trying import records from CSV file to MySQL table but only first row inserted. remaining not uploading to database
if (isset($_POST["upload_csv"])) {
$fileName = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0) {
$file = fopen($fileName, "r");
while (($column = fgetcsv($file, 10000, ",")) !== FALSE) {
$sqlInsert = "INSERT into price_dump (`stock_id`,`stock_price`,`previous_price`,`minute_set`)
values ('" . $column[0] . "','" . $column[1] . "','" . $column[2] . "','" . $column[3] . "')";
$result = mysqli_query($conn, $sqlInsert);
if (! empty($result)) {
$type = "success";
$message = "CSV Data Imported into the Database";
} else {
$type = "error";
$message = "Problem in Importing CSV Data";
}
}
}
}
if (isset($_POST["upload_csv"])) {
$fileName = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0) {
$file = fopen($fileName, "r");
$lines = file($_FILES["file"]["tmp_name"]);
foreach ($lines as $line) {
$column = explode(',', $line);
$sqlInsert = "INSERT into price_dump (`stock_id`,`stock_price`,`previous_price`,`minute_set`)
values ('" . $column[0] . "','" . $column[1] . "','" . $column[2] . "','" . $column[3] . "')";
$result = mysqli_query($conn, $sqlInsert);
if (! empty($result)) {
$type = "success";
$message = "CSV Data Imported into the Database";
} else {
$type = "error";
$message = "Problem in Importing CSV Data";
}
}
}
}
and maybe csv file separated by ;

Ubuntu 16.04 caching Php Variables?

I duplicated a folder full of scripts and edited the contents.
ex: /scripts -> /script-new
When I run a php script from this new file I seem to be having some weird issues.
php -f /scripts-new/pulldata.php
When I do this it seems to be using some variables from the old script that I have changed in the code.
/scripts/pulldata.php
$dbtable = "validclickvc";
/scripts-new/pulldata.php
$dbtable = "valid_click_ads";
Here is the mysql command that I am running
$sql = "INSERT INTO " . $dbtable . " ( COLUMN_NAMES ) " . " VALUES ( COLUMN_VALUES )";
And in my error log:
Error: INSERT IGNORE INTO validclickvc VALUES ( '--' )
What might be causing this?
EDIT:
Here is the whole script if it helps!
<?php
// Set some variables to connect to the FTP
$yesterday = date("Ymd", strtotime( '-1 days' ));
$filename = "vc_report_" . $yesterday . ".csv";
$sourcefile = "/***/" . $filename;
$localfile = "php://output";
$ftpserver = "***";
$ftpusername = "***";
$ftppassword = "***";
// Set some variabled to connect to rhe database
$dbhost = "***";
$dbname = "***";
$dbtable = "valid_click_ads";
$dbusername ="***";
$dbpassword = "***";
$fielddelimiter = ",";
$linedelimiter = "\r\n";
// Try to connect to the ftp server
$conn = ftp_connect($ftpserver) or die("Could not connect");
echo "Connected to FTP. \n";
// Try to login to the ftp server
if (ftp_login($conn, $ftpusername, $ftppassword)) {
echo "Logged in to FTP. \n";
} else {
echo "FTP login unsuccessful. \n";
}
ob_start();
// Try to open download today's report
$file = ftp_get($conn, $localfile, $sourcefile, FTP_BINARY);
if ($file) {
$csvcontent = ob_get_contents();
echo "File read successfully. \n";
} else {
echo "File was not read successfully. \n";
}
// Close the file and the connection to the FTP
ftp_close($conn);
echo "File and connection to the FTP closed. \n";
// Connect to the database
$con = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname);
if (!$con) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
} else {
echo "Connected to database. \n";
}
// Set row counter
$rows = 0;
// Set first
$first = true;
// Separate data by line
$lines = explode(PHP_EOL, $csvcontent);
// Insert lines of data
foreach ($lines as $line) {
if (!$first) {
$linearray = explode($fielddelimiter, $line);
print_r ($linearray);
$source_tag = $linearray[1];
if ( strpos( $source_tag, 'phone' ) !== false ) {
$source = "Smart Phone";
} else if ( strpos( $source_tag, 'desktop' ) !== false ) {
$source = "Desktop";
} else {
$source = "";
}
if ( $linearray[14] == "N/A" ) {
$tq = -1;
} else {
$tq = $linearray[14];
}
$sql = "SELECT affiliate_id, id, campaign_id, group_id, user_id, website_id FROM keywords WHERE affiliate_id = " . $linearray[7];
$result = $con->query($sql);
if ( $row = $result->fetch_assoc() ) {
$keyword_id = $row[ 'id' ];
$group_id = $row[ 'group_id' ];
$campaign_id = $row[ 'campaign_id' ];
$user_id = $row[ 'user_id' ];
$website_id = $row[ 'website_id' ];
} else {
$keyword_id = "";
$group_id = "";
$campaign_id = "";
$user_id = "";
$website_id = "";
}
$sql = "INSERT IGNORE INTO " . $dbtable . " ( market, source, device, searches, impressions, clicks, revenue, tq, website_id, user_id, campaign_id, group_id, affiliate_id, keyword_id ) " . " VALUES ( '" . $linearray[5] . "', " . $source . "', " . $linearray[4] . "', " . $linearray[8] . "', " . $linearray[9] . "', " . $linearray[10] . "', " . $linearray[12] . "', " . $tq . "', " . $website_id . "', " . $user_id . "', " . $campaign_id . "', " . $group_id . "', " . $affiliate_id . "', " . $keyword_id . "' )";
echo $sql;
if ($con->query($sql) === TRUE) {
$rows++;
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
} else {
$first = false;
}
}
$con->close();
echo "Inserted a total of " . $rows . " records.\n"
?>

Why i cannot use REPLACE.How do I UPDATE a row in a table or INSERT it if it doesn't exist?

I want to UPDATE a row in a table or INSERT it if it doesn't exist?
I have already read solution from this link. How do I UPDATE a row in a table or INSERT it if it doesn't exist?
So, i used replace but it did not work. It only added new row into the table but did not update anything.
this is my structure
<?php
define('ROOTPATH', __DIR__);
$output = [];
$output['result'] = [];
$output['image_path'] = [];
$applicationName = (isset($_POST) && array_key_exists('applicationName', $_POST)) ? $_POST['applicationName'] : 'applicationName';
if (empty($applicationName)) {
$output['result'][] = 'missing application name';
}
else if (is_array($_FILES) && array_key_exists('image', $_FILES) && array_key_exists('logo', $_FILES))
{
$upload_dir = '/upload_dir/';
$upload_path = ROOTPATH . $upload_dir;
$applicationName = $_POST['applicationName'];
$sql_field_list = ['applicationName'];
$sql_value_list = [$applicationName];
foreach ( $_FILES as $key => $upload) {
if($key != 'image' && $key != 'logo')
{
$output['result'][] = $key . ' is invalid image';
}
else
{
if ($upload['error'] == UPLOAD_ERR_OK &&
preg_match('#^image\/(png|jpg|jpeg|gif)$#', strtolower($upload['type'])) && //ensure mime-type is image
preg_match('#.(png|jpg|jpeg|gif)$#', strtolower($upload['name'])) ) //ensure name ends in trusted extension
{
$parts = explode('/', $upload['tmp_name']);
$tmpName = array_pop($parts);
$fieldname = ($key == 'image') ? 'bgBNPage' : 'logo';
$filename = $applicationName . '_' . $fieldname . '.' . pathinfo($upload["name"], PATHINFO_EXTENSION);
if (move_uploaded_file($upload["tmp_name"], $upload_path . $filename))
{
$sql_field_list[] = $fieldname;
$sql_value_list[] = $upload_dir . $filename;
$output['image_path'][$key] = $upload_dir . $filename;
}
else
{
$output['result'][] = $key . ' upload fail';
}
}
else
{
$output['result'][] = $key . ' error while upload';
}
}
}
//after upload complete insert pic data into database
$con = mysqli_connect("localhost", "root", "root", "museum");
if (!$con) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$fields = implode(', ', $sql_field_list);
$values = implode("', '", $sql_value_list);
$sql = "REPLACE INTO general (" . $fields . ") VALUES ('" . $values . "');";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
} else {
$output['result'][] = 'no file selected';
}
header('Content-type: application/json');
echo json_encode($output);
echo json_encode('finish');
?>
Can i use
if(logo or bgBNPage is enpty)
{
insert into database
}
else{
Update database
}
please tell me the correct syntax.
I'm guessing username is the field where, if it's a duplicate, you want to update. So, if username is a unique key, you can do something like:
insert into general ([fields]) values ([values])
on duplicate username update
[whatever]
I found the solution.
I use if else condition to proove it.
This is my code result
//after upload complete insert pic data into database
$con = mysqli_connect("localhost", "root", "root", "museum");
$sql = "SELECT logo,bgBNPage FROM general ";
$result = mysqli_query($con, $sql);
if (!$con) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$fields = implode(', ', $sql_field_list);
$values = implode("', '", $sql_value_list);
if(mysqli_num_rows($result) > 0)
{
$str_array = [];
for($i =0; $i < count($sql_field_list); $i++)
{
$str_array[] = $sql_field_list[$i] . "='" . $sql_value_list[$i] ."'";
}
$sql = 'UPDATE general SET ' . implode(',', $str_array);
//$sql = "UPDATE general SET (" . $fields . ") = ('" . $values . "');";
}
else
{
$sql = "INSERT INTO general (" . $fields . ") VALUES ('" . $values . "');";
}
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);

How to filter the repeated numbers in the Excel to send the data to MySQL and I want to show the alert message in Php?

The code i tried is for only exporting the excel data to MySql database.
$source = fopen('email.csv', "r");
$query = '';
while (($data = fgetcsv($source, 1000)) !== FALSE) {
for ($i = 1; $i < 2; $i++) {
$name[$i] = $data[0];
$email[$i] = $data[1];
$mobile[$i] = $data[2];
$query.="INSERT INTO table tablename (`name1`,`email`, mobile) VALUES ('" . $name[$i] . "','" . $email[$i] . "','" . $mobile[$i] . "') ;";
//return $query;
}
}
$connection->createCommand($query)->execute();
I want to filter the repeated numbers and to show the alert message for filtering the numbers... Is it possible?
Yes, possible:
Try this code to insert only unique data.
$source = fopen('email.csv', "r");
$query = '';
while (($data = fgetcsv($source, 1000)) !== FALSE) {
$duplicate_raw = false;
$name = $data[0];
$email = $data[1];
$mobile = $data[2];
if( in_array($name , $name_array[] ){
echo 'Alredy exists: ' . $name . '<br>';}
$duplicate_raw = true;
else{
$name_array[] = $name;}
if( in_array($mobile , $mobile_array[] ){
echo 'Alredy exists: ' . $mobile . '<br>';}
$duplicate_raw = true;
else{
$mobile_array[] = $mobile;}
if( in_array($email , $email_array[] ){
echo 'Alredy exists: ' . $email . '<br>';}
$duplicate_raw = true;
else{
$email_array[] = $email;}
if ($duplicate_raw == false){
$query.="INSERT INTO table tablename (`name1`,`email`, mobile) VALUES ('" . $name . "','" . $email . "','" . $mobile . "') ;";}//return $query;
}
$connection->createCommand($query)->execute();

Reading foreign characters in a CSV file

I have a script that takes a CSV file and uploads each row to a database. However, foreign characters in the file not just display wrong, but don't display at all.
For example, here is an "input" row, and what it would read like in the database:
"This café is amazing", "1000", "www.example.com"
"This caf", "1000", "www.example.com"
This is the script that does the upload:
header("Content-Type: text/plain; charset=utf-8");
if (!isset($_POST['form_id'])) {
header("Location: ./?error=form_id");
exit();
}
$form_id = $_POST['form_id'];
$csv = $_FILES['csv_file'];
if ($csv['size'] > 0) {
$handle = fopen($csv['tmp_name'], "r");
require_once("db.php");
$i = (!isset($_POST['csv_headers']) ? 1 : 0);
while ($data = fgetcsv($handle, 1000, ',', '"')) {
if ($i > 0) {
$data[2] = str_replace(" + ", "+", $data[2]);
if (strpos($data[3], "http") === false && $data[3] != "") {
$data[3] = "http://" . $data[3];
}
mysql_query("INSERT INTO exhibitor_lists SET form_id = $form_id, company_name = '" . addslashes($data[0]) . "', country = '" . addslashes($data[1]) . "', stand_number = '" . addslashes($data[2]) . "', web_address = '" . addslashes($data[3]) . "', logo_file = '" . addslashes($data[4]) . "', added_date = NOW()");
}
$i++;
}
} else {
header("Location: ./?error=csv_file");
exit();
}
mysql_close();
header("Location: ./?success=upload");
exit();
Even when setting the content type header(), I get the problem.
Save the CSV file in UTF8 before uploading it.

Categories