Importing data from Excel to MySQL showing text in different language - php

I am trying to import data from Excel to MySQL using PHP. The code I am using imports the data but the language is strange.
Below is the PHP code:
<?php
include_once("conn.php");
$filename= "Financial Sample.xlsx";
$file = fopen($filename, "r");
$count = 0; // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//print_r($emapData[0]);
//exit();
$count++; // add this line
if($count>1){ // add this line
//echo html_entity_decode("žūų");
//echo json_encode($emapData[0]);
$insert_q = "INSERT into questions(q_describe) values ('$emapData[0]')";
if($query_q=$mysqli->query($insert_q))
{
$final=array();
$final['status']="success";
$final['message']="Inserted Successfully";
}
else
{
$er = $mysqli->error;
$final['status']=$er;
$final['message']="Error";
}
echo json_encode($final);
} // add this line
}
fclose($file);
?>
Once imported, data is seen like this in phpMyAdmin:
Actual Excel is shown below:
Where am I going wrong?
Edit
Showing the structure of my table:

If you look at the structure of your table, you're looking for two fields: encoding and Collation.
Make sure they're set to cp1252 West European and latin1_swedish_ci respectively.

Related

Import certain csv/excel data to mysql database using PHP

Is there any way to select a certain csv/excel cells then import its data to database? I have a similar program but it only import the first, second, etc. columns.
So here's the php codes for reading excel data and input.
<?php
include 'db.php';
if(isset($_POST["Import"])){
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//It wiil insert a row to our subject table from our csv file`
$sql = "INSERT into subject (`SUBJ_CODE`, `SUBJ_DESCRIPTION`, `UNIT`, `PRE_REQUISITE`,COURSE_ID, `AY`, `SEMESTER`)
values('$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$emapData[7]')";
//we are using mysql_query function. it returns a resource on true else False on error
$result = mysqli_query( $conn, $sql );
if(! $result )
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"index.php\"
</script>";
}
}
fclose($file);
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"index.php\"
</script>";
//close of connection
mysqli_close($conn);
}
}
?>
It only import the selected columns
Example
Excel
What I want is to find a certain cell by reading the cell data and import the data below it. Here's visualization:
What I want to do:
Is there any way to do this? I need help. Thank you
Here is the sample program:
https://www.sourcecodester.com/tutorials/php/6989/how-import-excelcsv-file-mysql-database-using-php.html
If you want to do it for just once than you can use some online tools.
If you want to have a code for this than you can do by following code
$open = fopen("filename.csv", "r"); // This will open the file for you
$data = fgetcsv($Open, 1000, ","); // Read Line be Line
while (($data = fgetcsv($Open, 1000, ",")) !== FALSE)
{
// Read the data
}

importing excel sheet into mysql table with php

I want to import the excel sheet data into mysql table with php but i am getting these errors someone please get me out from this.. please look on php code only ignore html stuff.
<?php
include ("connection.php");
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = $filesop[1];
$email = $filesop[2];
$sql = mysql_query("INSERT INTO co (name, email) VALUES ('$name','$email')");
$c = $c + 1;
}
fcose($file);
if($sql){
echo "You database has imported successfully. You have inserted ". $c ." recoreds";
}else{
echo "Sorry! There is some problem.";
}
}
?>
this is excel sheet
in database it is showing different format
There are libraries excellibrary/php-excel-reader/excel_reader2.php and excellibrary/SpreadsheetReader.php
you can use these libraries to read your content and convert it into array.
Once you convert your spreadsheet data into an array, you can easily insert into database using iterations.

Inserting Hebrew text into mysql using php - blank

I have a problem when I upload csv file to mysql.
I used this code:
if(isset($_POST["submit"])) {
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
$row=1;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false) {
if ($row ==1) {
$row++;
continue;
}
$name = $filesop[0];
$phone = $filesop[1];
$sql = runsql("INSERT INTO messages_recipient (user_id,full_name, phone,date_added) VALUES ($SVARS[user_id],'$name','$phone',NOW())");
}
if($sql) {
echo "You database has imported successfully";
} else {
echo "Sorry! There is some problem.";
}
}
it's worked fine except when i upload csv file with hebrew values i get blank values in mysql.
i tried to change the type to text/long text without success.
the collation is: utf8_general_ci.
thanks for the help
You may be looking for:
mysqli_query("SET NAMES 'utf8'");
and
mysqli_query("SET CHARACTER SET utf8 ");
Use it before the query.
mysqli.set-charset:
http://php.net/manual/en/mysqli.set-charset.php

Php script to Import CSV with Arabic content

I have to build a script to import a CSV file, (With Arabic content in one coloumn).
I have been searching online and manage to convert my CSV file to UTF8
$filename = $_FILES["csv"]["tmp_name"];
$file = fopen($filename, "r");
$count = 0;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$count++;
if($count>1){
// tried to convert using below
$string_decoded = iconv("windows-1256", "utf-8", $emapData[2]);
// convert code above
$sql = "INSERT into `$table` (SurahNo,AyatNo,Ayat) values ('$emapData[0]','$emapData[1]','$string_decoded')";
echo $sql;
mysql_query($sql);
}
}
I tried to convert using iconv but still getting garbage content imported in mysql.
Imported content look like this
ط¨ظگط³ظ’ظ…ظگ ط§ظ„ظ„ظ‘ظ
Can share my CSV file if you wish.
Need help, spend hours searching.

Uploading a CSV file and importing to mysql giving an error

I am using the following script to import data into my mysql database from CSV files. The CSV is setup like this :
Name Postcode
fred hd435hg
bob dh345fj
Above is what it looks like in excel, in raw csv format viewed in notepad it looks like this :
name,postcode
frank,ng435tj
The problem I am having is for some reason the postcode column isnt getting imported at all, also the header row is getting imported as a record too, is it possible to make it skip the first row ?. I have been through the code and cant see why the postcode is not being pulled in, it is very odd.
<?php
//database connect info here
//check for file upload
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){
//upload directory
$upload_dir = "./csv";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
//move uploaded file to upload dir
if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
//error moving upload file
echo "Error moving file upload";
}
//open the csv file for reading
$handle = fopen($file_path, 'r');
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
//Access field data in $data array ex.
$name = $data[0];
$postcode = $data[1];
//Use data to insert into db
$sql = sprintf("INSERT INTO test (name, postcode) VALUES ('%s',%d)",
mysql_real_escape_string($name),
$postcode
);
mysql_query($sql) or (mysql_query("ROLLBACK") and die(mysql_error() . " - $sql"));
}
//delete csv file
unlink($file_path);
}
?>
Your CSV file seems to be a TSV file actually. It doesn't use commas, but tabulators for separating the fields.
Therefore you need to change the fgetcsv call. Instead of ',' use the tab:
while (($data = fgetcsv($handle, 1000, "\t") ...
And to also skip the header row, add another faux fgetcsv before the while block:
fgetcsv($handle);
while (...) {
That will skip the first line. (A simple fgets would also do.)
Oh, just noticed: The postcode might also get dropped because you concat it into the string as decimal with the sprintf placeholder %d for $postcode. Should that field actually contain lettery, like in your example, then that wouldn't work. -- Though I presume that's just a wrong example printout.
Try this one.
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false)
{
$username = $fileop[0];
$name = $fileop[1];
$address = $fileop[2];
$sql = mysql_query("INSERT INTO ...... ");
}

Categories