I have a table in MYSQL where I wish to have the option that my customer can upload a CSV file. By default I want this to add information which isn't there and automatically update it if there is information there.
These are the columns I have:
id customer_name customer_name_letterhead customer_notes systype status signaltype verification address postcode telephone mobile mobiletwo email mainarea installation Contract expiration SPA nservice maintenance monitoring MS certdate
I already know that I need to have an excel document with all of these in the headers of the rows. E.g A1-V1 has those headers.
edit:
I have made this:
<?PHP if(isset($_POST['SUBMIT']))
{
$fname = $_FILES['sel_file']['name'];
$chk_ext = explode(".",$fname);
if(strtolower($chk_ext[1]) == "csv")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql = "INSERT into Customers(id,customer_name,customer_name_letterhead,customer_notes,systype,status,signaltype,verification,address,postcode,telephone,mobile,mobiletwo,email,mainarea installation,Contract,expiration,SPA,nservice,maintenance,monitoring,MS,certdate) values('$data[0]','$data[1]','$data[2]''$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]','$data[14]','$data[15]','$data[16]','$data[17]','$data[18]','$data[19]','$data[20]','$data[21]','$data[22]','$data[23]','$data[24]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}?>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post'>
Import File : <input type="file" name="sel_file" id="sel_file">
<input type='submit' name='submit' value='submit'>
</form>
Upon clicking submit, nothing happens.
Here is a picture of my csv file:
I ended up searching for a video on YouTube which really did help. It ended up giving me this:
<?PHP
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000, ",")) !== false)
{
$customer_name = $fileop[0];
$customer_name_letterhead = $fileop[1];
$customer_notes = $fileop[2];
$systype = $fileop[3];
$status = $fileop[4];
$signaltype = $fileop[5];
$verification = $fileop[6];
$address = $fileop[7];
$postcode = $fileop[8];
$telephone = $fileop[9];
$mobile = $fileop[10];
$mobiletwo = $fileop[11];
$email = $fileop[12];
$mainarea = $fileop[13];
$installation = $fileop[14];
$Contract = $fileop[15];
$expiration = $fileop[16];
$SPA = $fileop[17];
$nservice = $fileop[18];
$maintenance = $fileop[19];
$monitoring = $fileop[20];
$MS = $fileop[21];
$certdate = $fileop[22];
$sql = mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO Customers (
customer_name,
customer_name_letterhead,
customer_notes,
systype,
status,
signaltype,
verification,
address,
postcode,
telephone,
mobile,
mobiletwo,
email,
mainarea,
installation,
Contract,
expiration,
SPA,
nservice,
maintenance,
monitoring,
MS,
certdate
) VALUES (
'$customer_name',
'$customer_name_letterhead',
'$customer_notes',
'$systype',
'$status',
'$signaltype',
'$verification',
'$address',
'$postcode',
'$telephone',
'$mobile',
'$mobiletwo',
'$email',
'$mainarea',
'$installation',
'$Contract',
'$expiration',
'$SPA',
'$nservice',
'$maintenance',
'$monitoring',
'$MS',
'$certdate'
)");
if($sql)
{
echo 'Uploaded '. $sql . ' entries';
}
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<br>
<input type="submit" name="submit" value="Upload CSV File">
</form>
not used it myself but have you tried this,
http://php.net/manual/en/function.str-getcsv.php
you could also try breaking the csv up into lines using explode on \n and then splitting it up further based on the ,.
once you have all the chunks push it into the database.
Related
No error messages appear on the page. Upload File button works. Upload button doesn't trigger db insert but the page refreshes as if it did.
I am not sure if the array of data from Excel is being coded correctly on the INSERT Into command. Any help is appreciated but PLEASE keep it simple. I am not a seasoned developer. Very green and primarily use procedural coding. If you use an experienced term, don't assume I know what it means.
PHP - if Post Submit button code. The errorMsg doesn't display if no file is attached and submit button is clicked
var_dump($_POST);
if (isset($_POST['submit'])) {
//print_r($_FILES);
$ok = 'true';
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file, "r");
echo ++$x;
if ($handle !== FALSE){
$errorMsg = "<br /><div align='center'><font color='red'>Please select a CSV file to import</font></div>";
$ok = 'false';
echo ++$x;
PHP continued - I'm not seeing the uploaded file populate the database
} else {
print_r(fgetcsv($handle));
while(($filesop = fgetcsv($handle, 1000, ",")) !== FALSE){
$email = mysqli_real_escape_string($con_db, $filesop[0]);
$f_name = mysqli_real_escape_string($con_db, $filesop[1]);
$l_name = mysqli_real_escape_string($con_db, $filesop[2]);
$password = md5(mysqli_real_escape_string($con_db, $filesop[3]));
$zipcode = mysqli_real_escape_string($con_db, $filesop[4]);
$co_id = mysqli_real_escape_string($con_db, $filesop[5]);
$employee = mysqli_real_escape_string($con_db, $filesop[6]);
$assessment_ct = mysqli_real_escape_string($con_db, $filesop[7]);
echo ++$x;
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( strlen($email) > 0) {
echo ++$x;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo ++$x;
$ok = 'false';
$errorMsg .= 'E-mail address is not correct';
}
}
// error handling for password
if (strlen($password) >= 5) {
echo ++$x;
$ok = 'true';
} else {
echo ++$x;
$ok = 'false';
$errorMsg .= 'Your password is too short (please use at least 5 characters)';
}
// If the tests pass we can insert it into the database.
if ($ok == 'true') {
echo ++$x;
$sql = mysqli_query($con_db, "INSERT INTO `myMembers` (email, f_name, l_name, password, zipcode, co_id, employee, assessment_ct) VALUES ('$email', '$f_name', '$l_name', '$password', '$zipcode', '$co_id', '$employee', '$assessment_ct')") or die ("Shit is not working");
} else {// close if $ok == 'true'
$result = print_r($handle);
echo $handle.'<br>';
echo ++$x;
}
} // close WHILE LOOP
fclose($handle);
if ($sql !== FALSE) {
echo ++$x;
$successMsg = 'Your database has imported successfully!';
//print_r($_FILES);
//header('excel_import.php');
} else {
echo ++$x;
$errorMsg = 'Sorry! There is some problem in the import file.';
//print_r($_FILES);
//header('excel_import.php');
}
} // close if (!is_null($file)){
} // close if $post = submit
HTML Code for the form to submit uploaded file
<form enctype="multipart/form-data" method="POST" action="excel_import.php">
<div align="center">
<label>File Upload: </label><input type="file" id="csv_file" accept=".csv" >
<p>Only Excel.CSV File Import</p>
<input type="submit" name="csv_file" class="btn myButton" value="Upload">
</div>
</form>
</div>
<div><?php echo $errorMsg; ?><?php echo $successMsg; ?></div>
Your submit button does not have a name - and thus $_POST['submit'] is not set. Also, fclose($file) should be fclose($handle). And you should be checking with $handle !== FALSE and $sql !== FALSE rather than with is_null().
I am trying to import data from xls to mysql via php. I am facing issue in save UTF-8 text via it. I am getting it saved as ???????. My database table structure is utf8_general_ci as well my php code is like below
<?php
$con = mysqli_connect('localhost', 'myuser', 'mypass', 'mydb');
if(isset($_POST["submit"]))
{
mysqli_query($con,'SET character_set_results=utf8');
mysqli_query($con,'SET names=utf8');
mysqli_query($con,'SET character_set_client=utf8');
mysqli_query($con,'SET character_set_connection=utf8');
mysqli_query($con,'SET character_set_results=utf8');
mysqli_query($con,'SET collation_connection=utf8_general_ci');
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$i = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$option1 = $filesop[0];
$option2 = $filesop[1];
$option3 = $filesop[2];
$option4 = $filesop[3];
$correctans = $filesop[4];
$question_text = $filesop[5];
$cat_id = $filesop[6];
$sub_cat_id = $filesop[7];
$level_id = $filesop[8];
$quesimage = $filesop[9];
$sql = mysqli_query($con,"INSERT IGNORE INTO questions (option1, option2,option3,option4,correctans,question_text,cat_id,sub_cat_id,level_id,quesimage) VALUES ('".$option1."','".$option2."','".$option3."','".$option4."','".$correctans."','".$question_text."','".$cat_id."','".$sub_cat_id."','".$level_id."','".$quesimage."')");
$i = $i + 1;
}
//echo $sql;
if($sql)
{
echo "You database has imported successfully. You have inserted ". $i ." records";
}
else
{
echo "Sorry!";
}
}
?>
<html>
<head>
<title>Import Questions</title>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload Excel File : <input type="file" name="file" /><br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
its working fine with English Text but getting issue in Hindi or Gujarati Text. How can I solve it ?
Thanks
Note that when using fgetcsv() function for reading data the locale setting is taken into account. If LANG is e.g. en_US.UTF-8, files in one-byte encoding are read wrong by this function.
You can try another thing - to convert your .csv document on-the-fly (change the UCS-2 with the your file encoding):
function parse_csv($filename) {
if (($handle != fopen($filename, "r"))) return false;
while (($cols = fgetcsv($handle, 1000, "\t")) !== FALSE) {
foreach( $cols as $key => $value ) {
$cols[$key] = trim( $cols[$key] );
$cols[$key] = iconv('UCS-2', 'UTF-8', $cols[$key]."\0") ;
$cols[$key] = str_replace('""', '"', $cols[$key]);
$cols[$key] = preg_replace("/^\"(.*)\"$/sim", "$1", $cols[$key]);
}
echo var_dump($cols); //This will display an array of your data
}
}
Using the same idea of the previous post, with a little modification:
function global_client_charset($charset){
if(!isset($charset)){
$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(strrpos($user_agent,"linux")){
$GLOBALS["CHARSET"] = "UTF-8";
}else if(strrpos($user_agent,"windows")){
$GLOBALS["CHARSET"] = "ISO-8859-1";
}
}else{
$GLOBALS["CHARSET"] = $charset;
}
}
function toUTF8($data){
if($GLOBALS["CHARSET"] === "ISO-8859-1"){
return iconv("ISO-8859-1", "UTF-8", trim($data));
}else if($GLOBALS["CHARSET"] === "UTF-8"){
return trim($data);
}else{
return trim($data);
}
}
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$i = 0;
//do you know the charset you are receiving ??
//global_client_charset("ISO-8859-1");
global_client_charset();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$option1 = $filesop[0];
$option2 = $filesop[1];
$option3 = $filesop[2];
$option4 = $filesop[3];
$correctans = $filesop[4];
$question_text = $filesop[5];
$cat_id = $filesop[6];
$sub_cat_id = $filesop[7];
$level_id = $filesop[8];
$quesimage = $filesop[9];
$query = "INSERT IGNORE INTO questions (option1, option2,option3,option4,correctans,question_text,cat_id,sub_cat_id,level_id,quesimage) VALUES ('".
$option1."','".$option2."','".$option3."','".$option4."','".$correctans."','".$question_text."','".
$cat_id."','".$sub_cat_id."','".$level_id."','".$quesimage."')";
//echo toUTF8($query); die();
$sql = mysqli_query($con,toUTF8($query));
$i = $i + 1;
}
if($sql)
{
echo "You database has imported successfully. You have inserted ". $i ." records";
}
else
{
echo "Sorry!";
}
}
?>
<html>
<head>
<title>Import Questions</title>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload Excel File : <input type="file" name="file" /><br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
I have been trying this code I found from this site here: https://www.johnboyproductions.com/blog/tutorial-import-a-csv-file-using-php-and-mysql
It works perfectly for me locally, but when I try the code on a live site. It says that the data is imported but does not reflect in the database. I am adding the code below:
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysqli_query("INSERT INTO tablename VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
//redirect
header('Location: filename.php?success=1'); die;
}
That's the functionality part, I will post the form section below:
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
Any help will be greatly appreciated. Thanks
I have tried another code that was used initially which is working now:
if(isset($_POST['Submit']))
{
if ($_FILES['csv']['size'] > 0)
{
//get the csv file
$file = $_FILES['csv']['tmp_name'];
$handle = fopen($file,"r");
$firstRow = true;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if($firstRow) { $firstRow = false; }
else {
$str="INSERT INTO tablename VALUES
('' ,
'".addslashes($data[0])."',
'".addslashes($data[1])."'
) ";
$result = mysqli_query($connection,$str);
if($result)
$cnt++;
}
}
fclose($handle);
//redirect
// header('Location: filename.php?success=1'); die;
}
}
I have a csv file. I'm trying to read this file and import data to mysql database.
For example
OrderID,ProductId,ProductDescription
100001962,15,Product1
"",32,Product2
"",31,Product3
100001546,24,Product4
How can i have my database like
100001962,15,Product1
100001962,32,Product2
100001962,31,Product3
100001546,24,Product4
new.php
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" />
</form>
</body>
</html>
upload.php
header('Content-Type: text/html; charset=UTF-8');
require_once 'db.php';
if($_FILES['csv']['error'] == 0){
$name = $_FILES['csv']['name'];
$ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
$type = $_FILES['csv']['type'];
$tmpName = $_FILES['csv']['tmp_name'];
// check the file is a csv
if($ext === 'csv'){
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
// necessary if a large csv file
set_time_limit(0);
mysqli_set_charset($connection,"utf8");
$success = 0;
$nosuccess = 0;
while(( $data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// number of fields in the csv
$csv[$row]['col1'] = str_replace("'", " ", $data[0]);//orderid
$csv[$row]['col2'] = str_replace("'", " ", $data[1]);//productid
$csv[$row]['col3'] = str_replace("'", " ", $data[2]);//productdesc
if ($csv[$row]['col1']==0){
if ($csv[$row-1]['col1']!=0){
$sql = "INSERT INTO csv (orderid, orderdate, orderstatus) VALUES ('". $csv[$row-1]['col1']."','". $csv[$row-1]['col2']."','". $csv[$row-1]['col3']."')";
}
if ($csv[$row-2]['col1']!=0){
$sql = "INSERT INTO csv (orderid, orderdate, orderstatus) VALUES ('". $csv[$row-2]['col1']."','". $csv[$row-2]['col2']."','". $csv[$row-2]['col3']."')";
}
//etc
}
else
{
$sql = "INSERT INTO csv (orderid, orderdate, orderstatus) VALUES ('". $csv[$row]['col1']."','". $csv[$row]['col2']."','". $csv[$row]['col3']."')";
}
mysqli_query($connection, $sql);
}
}
}
but doesn't work
hallo guys sorry for bothering ..the code is now working..i had so many problems on my previous posts but this is the last problems i am getting..i noticed when i insert the csv file it correctly inserting..but if i refresh the page data is being duplicated due to post data..how do i make this not to repeat? i am trying to paste this but i get an error
SAVED_REQUEST = $_REQEUST;
$SAVED_POST = $_POST;
$SAVED_GET = $_GET;
// FINALLY, IN YOUR LAST LINE ERASE THE PROBLEM VARIABLES...
$_REQUEST = $_POST = $_GET = NULL;
<?php $_REQUEST = $_POST = $_GET = NULL; ?>
this is my previous script
<form enctype="multipart/form-data" method="POST" action="" >
CSV<input type="file" name="file" />
<input type="submit" value="submit" name="submit"/>
</form>
<?php
$connection = mysql_connect("localhost","root","")
or die ("Couldn't connect to server");
$db = mysql_select_db("map", $connection)
or die ("Couldn't select database");
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
if (($handle = fopen($file, "r")) !== FALSE) {
while ($fileop = fgetcsv($handle,1000,",","'"))
{
$a = $fileop[0];
$b = $fileop[1];
$c = $fileop[2];
$d = $fileop[3];
$e = $fileop[4];
$f = $fileop[5];
$sql = mysql_query("INSERT INTO hzy3o_zhgooglemaps_markers (title, addresstext, published, baloon, icontype, mapid)
values('$a', '$b', '$c', '$d', '$e', '$f')");
}
}
}
After successful insert make redirect to the same page:
header("Location: http://www.yourwebsite.com/yourpage"); /* Redirect browser */
exit();
Also make a check in database to prevent data duplication.
Your refactored code:
<?php
if (isset($_POST['submit'])) {
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
if (($handle = fopen($file, "r")) !== false) {
while ($fileop = fgetcsv($handle, 1000, ",", "'")) {
list($a, $b, $c, $d, $e, $f) = $fileop;
$sql = mysql_query("
INSERT INTO hzy3o_zhgooglemaps_markers (title, addresstext, published, baloon, icontype, mapid)
values('$a', '$b', '$c', '$d', '$e', '$f')
");
}
}
}
?>
<?php if (isset($_POST) && count($_POST) > 0):?>
<form enctype="multipart/form-data" method="POST" action="" >
CSV<input type="file" name="file" />
<input type="submit" value="submit" name="submit"/>
</form>
<?php else: ?>
<?php
header("Location: http://www.shambani.org /index.php?option=com_zhgooglemap&view=zhgooglemap&id=1&mapzoom=13&placemarklistid=&explacemarklistid=&grouplistid=&categorylistid=¢erplacemarkid=¢erplacemarkaction=&externalmarkerlink=0&mapwidth=&mapheight=&Itemid=177");
exit();
?>
Try it.
many thanks to gurus who Assisted me to Develope this.. i thank you very much
<?php
$connection = mysql_connect("localhost","root","")
or die ("Couldn't connect to server");
$db = mysql_select_db("map", $connection)
or die ("Couldn't select database");
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
if (($handle = fopen($file, "r")) !== FALSE) {
while ($fileop = fgetcsv($handle,1000,",","'"))
{
$a = $fileop[0];
$b = $fileop[1];
$c = $fileop[2];
$d = $fileop[3];
$e = $fileop[4];
$f = $fileop[5];
$sql = mysql_query("INSERT INTO hzy3o_zhgooglemaps_markers (title, addresstext, published, baloon, icontype, mapid)
values('$a', '$b', '$c', '$d', '$e', '$f')");
}
}
}
?>
<?php
if (isset($_POST) && count($_POST) > 0) {
header("Location: http://localhost/map/"); /* Redirect browser */
exit();
}
?>
<form enctype="multipart/form-data" method="POST" action="" >
CSV<input type="file" name="file" />
<input type="submit" value="submit" name="submit"/>
</form>