Reading foreign characters in a CSV file - php

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.

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 ;

Upload file not working if checking for uploaded files is on the code

The images are uploading normally, but I want an "else if" to check if there is any file selected. This is working:
<?php
session_start();
include('includes/conexao.php');
$fileinfo=PATHINFO($_FILES["image"]["name"]);
$newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename);
$location="images/perfis/" . $newFilename;
$todas_fotos = mysqli_query($conexao, "select * FROM esc_usuarios_fotos WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
if( mysqli_num_rows($todas_fotos) > 0) {
//$path=$location;
//if(unlink($path)) echo "Deleted file ";
mysqli_query($conexao,"UPDATE esc_usuarios_fotos SET img_local = '$location' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
}
else if( mysqli_num_rows($todas_fotos) == 0)
{
mysqli_query($conexao,"insert into esc_usuarios_fotos (img_local, img_usu_codigo) values ('$location', '" . $_SESSION['codigo'] . "')");
}
else {
};
header('location:perfil.php');
?>
It inserts if there isn't an image, but if there is, it updates. But when I add:
else if (empty($_FILES['image']['name']))
{
header('location:perfil.php');
}
It returns me undefined index: extension on line 5. How to go?
Rewrite the code as follows. Here we are checking whether the file is not available at the beginning of the code and redirect if no file is found.
<?php
session_start();
if (empty($_FILES['image']['name']))
{
header('location:perfil.php?error=1');
return;
}
include('includes/conexao.php');
$fileinfo=PATHINFO($_FILES["image"]["name"]);
$newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["image"]["tmp_name"],"images/perfis/" . $newFilename);
$location="images/perfis/" . $newFilename;
$todas_fotos = mysqli_query($conexao, "select * FROM esc_usuarios_fotos WHERE
img_usu_codigo = '" . $_SESSION['codigo'] . "'");
if( mysqli_num_rows($todas_fotos) > 0) {
//$path=$location;
//if(unlink($path)) echo "Deleted file ";
mysqli_query($conexao,"UPDATE esc_usuarios_fotos SET img_local = '$location' WHERE img_usu_codigo = '" . $_SESSION['codigo'] . "'");
}else {
mysqli_query($conexao,"insert into esc_usuarios_fotos (img_local, img_usu_codigo) values ('$location', '" . $_SESSION['codigo'] . "')");
}
and in the perfil.php you should put
window.onload = function(){
var url = new URL(window.location.href);
var error = url.searchParams.get("error");
if(error==1)
alert("No file uploaded");
}

Retrieving data in php

I've created a page where I've place for updating the attachment. While doing so, if a file with same name, size, extension is attached, the attachment table need not be updated. This is the scenario. This is how I tried to do:
else if($mode == "attachment_update") {
$id = intval(mysqli_real_escape_string($mysqli, $_REQUEST["_id"]));
$upload_directory = "upload/attachment/";
$result = file_upload("attachment", "../".$upload_directory);
$file_name = '".addslashes($result[file_name])."';
write_log($file_name);
$file_extension = '".$result[file_extension]."';
write_log($file_extension);
$file_size = '".$result[file_size]."';
write_log($file_size);
$uploaded_file_name = '".$result[uploaded_file_name]."';
write_log($uploaded_file_name);
$uploaded_file_path = '".$upload_directory.$result[uploaded_file_name]."';
write_log($uploaded_file_path);
$query_select = "SELECT
file_name,
file_extension,
file_size,
uploaded_file_name,
uploaded_file_path
FROM
attachments
WHERE
id = 'id';";
$result1 = mysqli_query($mysqli, $query_select) or throwexception(mysqli_error($mysqli));
$row = mysqli_fetch_row($result1);
write_log($row[0]);
write_log($row[1]);
write_log($row[2]);
write_log($row[3]);
write_log($row[4]);
if($row[0] == $file_name &&
$row[1] == $file_extension &&
$row[2] == $file_size &&
$row[3] == $uploaded_file_name &&
$row[4] == $uploaded_file_path)
{
write_log("inside if");
} else {
if($result[status] == true) {
$query = "UPDATE
attachments
SET
file_name = '".addslashes($result[file_name])."',
file_extension = '".$result[file_extension]."',
file_size = '".$result[file_size]."',
uploaded_file_name = '".$result[uploaded_file_name]."',
uploaded_file_path = '".$upload_directory.$result[uploaded_file_name]."',
recorded_by = '$recorded_by',
recorded_datetime = '$recorded_datetime'
WHERE
id = 'id';";
mysqli_query($mysqli, $query) or throwexception(mysqli_error($mysqli));
}
}
echo json_encode(array("message" => "Updated successfully"));
exit;
}
The if condition does the thing. If all are true, the table will not be updated. If even any one fails, the table will be updated.
Here the problem is $file_name, $file_extension, $file_size, $uploaded_file_name are going null. I don't know how to retrieve it. Can someone tell how to retrieve those data, so that if can check it with the if condition?
In your case, You do not need to fire select query. just add AND condition in update query.
if ($mode == "attachment_update") {
$id = intval(mysqli_real_escape_string($mysqli, $_REQUEST["_id"]));
$upload_directory = "upload/attachment/";
$result = file_upload("attachment", "../" . $upload_directory);
$file_name = '".addslashes($result[file_name])."';
write_log($file_name);
$file_extension = '".$result[file_extension]."';
write_log($file_extension);
$file_size = '".$result[file_size]."';
write_log($file_size);
$uploaded_file_name = '".$result[uploaded_file_name]."';
write_log($uploaded_file_name);
$uploaded_file_path = '".$upload_directory.$result[uploaded_file_name]."';
write_log($uploaded_file_path);
$query = "UPDATE
attachments
SET
file_name = '" . addslashes($result[file_name]) . "',
file_extension = '" . $result[file_extension] . "',
file_size = '" . $result[file_size] . "',
uploaded_file_name = '" . $result[uploaded_file_name] . "',
uploaded_file_path = '" . $upload_directory . $result[uploaded_file_name] . "',
recorded_by = '$recorded_by',
recorded_datetime = '$recorded_datetime'
WHERE
id = 'id'
and file_name <> '" . addslashes($result[file_name]) . "',
and file_extension = '" . $result[file_extension] . "',
and file_size = '" . $result[file_size] . "',
and uploaded_file_name = '" . $result[uploaded_file_name] . "',
and uploaded_file_path = '" . $upload_directory . $result[uploaded_file_name] . "',
;";
mysqli_query($mysqli, $query) or throwexception(mysqli_error($mysqli));
echo json_encode(array("message" => "Updated successfully"));
exit;
}
Your question need more clarity.
Can you share the function,
$result = file_upload("attachment", "../".$upload_directory);
Are you able to log the values of $filename and $row?
write_log($file_name);
AND
write_log($row[0]);

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();

PHP csv upload works on mac but not windows

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';
?>

Categories