How can I import data from an XLS file to MySQL? - php

As I am trying to import MS Excel data to MySQL data base
using the following code:
<?php
$db_username="root"; //database user name
$db_password="";//database password
$db_database="hr_mysql"; //database name
$db_host="localhost";
mysql_connect($db_host,$db_username,$db_password);
#mysql_select_db($db_database) or die( "Unable to connect to database.");
$handle = fopen("UploadIt.xls", "r"); //test.xls excel file name
if ($handle)
{
$array = explode("\n", fread($handle, filesize("UploadIt.xls")));
}
$total_array = count($array);
$i = 0;
$Leave_Type_Id1="LTY001";
$Leave_Type_Id2="LTY002";
while($i < $total_array)
{
$data = explode(",", $array[$i]);
//$sql = "insert into test values ('$data[0]','$data[1]')";
$sql = "update `hs_hr_employee_leave_quota` set `no_of_days_allotted`= {$data[0]} WHERE `employee_id`= {$data[0]} and `leave_type_id`= '{$Leave_Type_Id1}'";
$result = mysql_query($sql);
$sql = "update `hs_hr_employee_leave_quota` set `no_of_days_allotted`= {$data[2]} WHERE `employee_id`= {$data[0]} and `leave_type_id`= '{$Leave_Type_Id2}'";
$result = mysql_query($sql);
$i++;
}
if($result==false)
echo "Not succed";
else
{
echo "completed";
}
?>
And my .xls sheet is:
But I am getting error saying
htdocs\Verify\XL_To_DBTable.php line 28 - Undefined offset: 2
|1|2|5|
|2|3|5|
|3|3|4|
|4|3|9|
|5|4|1|
(Assume above one as xls sheet only)

You need to properly read the file as an MS Excel file. You are treating it as an ascii text file. You could manually dump the file to CSV format and parse it using similar logic to what you have already. Or you could use:
PHP Excel File Reader
and use that to parse the file, get the contents and then create the appropriate queries to be executed in mysql.

Related

Importing data from Excel to MySQL showing text in different language

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.

Trying to write Php fwrite XML file from mysql query

I am trying to write some code that grabs a CSV file pulls the relevant postcode column then looks up that postcode in a MySql database which has longitude and latitude fields then save them to an XML file so it can be used in a different program
I think this code piece is all working, but for some reason, it only outputs the last field of the query :
//Open the file.
$fileHandle = fopen("test.csv", "r");
$postcode = array();
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
array_push($postcode, $row[40]);
}
$postcodefil = (array_unique($postcode));
$postcodefil = str_replace(' ', '', $postcodefil);
$postcodefil = preg_replace('/\s+/', '', $postcodefil);
//print_r($postcodefil);
foreach ($postcodefil as $value) {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT postcode, latitude, longitude FROM postcode WHERE postcode='$value' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myfile = fopen("test.xml", "w") or die("Unable to open file!");
$lat = $row["latitude"];
$lng = $row["longitude"];
fwrite($myfile, $lat."testss".$lng."\n");
echo $lat;
echo $lng;
echo "<br />";
}}
} // end of foreach
$conn->close();
however when i run it, it echo's correctly
50.822398-0.139938
51.444908-1.295341
50.841951-0.842508
51.308504-0.551835
etc.... etc...
but the Fwrite just outputs the last line
51.120916testss-0.599545
I' m totally confused by this. Please forgive me if it's something basic that I've over looked and thanks in advance.
The problem is that you open the file in each loop, this overwrites the previous data...
$myfile = fopen("test.xml", "w") or die("Unable to open file!");
while($row = $result->fetch_assoc()) {
So move the open outside the loop.
The second issue is that you aren't writing XML at all. You need to do something like...
$xml = simplexml_load_string("<coords />");
while($row = $result->fetch_assoc()) {
$newCoord = $xml->addChild("coord");
$newCoord->addChild("latitude", $row["latitude"]);
$newCoord->addChild("longitude", $row["longitude"]);
}
$xml->saveXML("test.xml");
This will generate a simple XML file, you will need to set the element names as appropriate.
First thing put the connection outside of the foreach loop, and the fopen outside the while
loop.
You open the xml file in the 'w' mode means according to the doc
Open for writing only; place the file pointer at the beginning of the
file and truncate the file to zero length. If the file does not exist,
attempt to create it.
You need append mode 'a'
Open for writing only; place the file pointer at the end of the file.
If the file does not exist, attempt to create it. In this mode,
fseek() has no effect, writes are always appended.
This will work for you. But you still making a db request per postalcode, i would suggest to collect all the postal code you need to query and make one db request to database with sql IN operator.

cannot upload csv file and get error C:\xampp\tmp\php9F4F.tmp

I'm working on a website that required me to create function to upload .csv file.
When upload the file, it says wrong format, and it display this message:
C:\xampp\tmp\php9F4F.tmp
p/s:I already convert the excel file into .csv comma delimited format and still get error while uploading.
What should I do to resolve the error and then get to upload the csv file into my database?
stdreport.php : //im using the same code from import.php in here to connect it with database
<?php
$SQLSELECT = "SELECT stdCard, stdName, stdProgram, stdCourseDesc, stdCampus
FROM student
ORDER BY stdID
LIMIT 0,20";
$result_set = mysql_query($SQLSELECT, $conn);
while($row = mysql_fetch_array($result_set))
{
?>
import.php
<?php
$conn=mysql_connect("localhost","root","") or die("Could not connect");
mysql_select_db("dashboard",$conn) or die("could not connect database");
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 student
(`stdID`, `stdCard`, `stdName`,
`stdOfficialEmail`,`stdEmail`,
`stdContNum`,`stdCourseDesc`, `stdCampus`,
`accessDate`)
values('$emapData[1]','$emapData[2]','$emapData[3]',
'$emapData[4]','$emapData[5]',
'$emapData[6]', '$emapData[7]','$emapData[8]',
'$emapData[9]')";
//we are using mysql_query function. it returns a resource on true else False on error
$result = mysql_query( $sql, $conn );
if(! $result ) {
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"stdreport.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 = \"stdreport.php\"
</script>";
//close of connection
mysql_close($conn);
}
}
?>
When you convert the excel file to CSV then there is two type of formate CSV UTF-8 (comma delimited ) and the second one is CSV (comma delimited ), use the second option I have also attached the screenshot.

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.

CSV into MySQL using PHP

I'm trying to import data from my students.csv file into mysql using php. The entries in the csv file is in such a way that column (student_number, fname, lname, level) will be inserted into biodata table..
I'm also uploading the student.csv file from my computer.
When I run the page I dont get anything out on the screen.
session_start();
require('includes/dbconnect.php');
require 'includes/header.inc.php';
//check for file upload
if (isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
//upload directory
$upload_dir = "C:\Users\DOTMAN\Documents\students.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');
//turn off autocommit and deletethe bio data
mysql_query("SET AUTOCOMMIT=0");
mysql_query("BEGIN");
mysql_query("TRUNCATE TABLE biodata") or die(mysql_error());
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
//Access field data in $data array ex.
$student_number = $data[0];
$fname = $data[1];
$lname = $data[2];
$level = $data[3];
//Use data to insert into db
$query = "INSERT INTO biodata (student_number, fname, lname, level)
VALUES ('$student_number', '$fname', '$lname', '$level')";
mysql_query($query) or die (mysql_error());
}
}
I'd suggest you to upload CSV-file with LOAD DATA INFILE command. This is fast method.
if you only need to do this once, i would consider using something like: http://csv2sql.com/
One immediate issue I can see is here:
$upload_dir = "C:\Users\DOTMAN\Documents\students.csv";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
You are already assigning the entire path, including the file name, to the $upload_dir variable - and then you're appending the uploaded file name again.
If you think there are errors in your code, start by adding
ini_set('display_errors', 1);
error_reporting(E_ALL);
to the beginning of your PHP code and fix any warnings/errors displayed. You can then turn off printing error messages by changing the second parameter to 0 in the first call.
Have u debug the $_FILES:
print_r($_FILES);
before doing any thing
Solution using PHP
$file = 'path/to.csv';
$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
if($line_num==0) { continue; } //escape the header column
$arr = explode(",",$line);
$column1= $arr[0];
$column2= $arr[1];
echo $column1.$column2."<br />";
//put the mysql insert statement here
}

Categories