Import excel/ csv file into phpmyadmin using php - php

I'm trying to write a code that will upload a document directly to phpMyAdmin using PHP. I tried this code and It looks like it works and there are no errors, but the data was not uploaded to the database..
Can someone please help point out the problem?
<?php
$host="localhost";
$username = "root";
$password = "";
$database= "schoolydb";
$connect = new mysqli($host,$username,$password,$database);
$connect ->set_charset("utf8");
$message = '';
if(isset($_POST["upload"]))
{
if($_FILES['product_file']['name'])
{
$filename = explode(".", $_FILES['product_file']['name']);
if(end($filename) == "csv")
{
$handle = fopen($_FILES['product_file']['tmp_name'], "r");
while($data = fgetcsv($handle))
{
$student_id = mysqli_real_escape_string($connect, $data[0]);
$student_login = mysqli_real_escape_string($connect, $data[1]);
$student_password = mysqli_real_escape_string($connect, $data[2]);
$student_first_name = mysqli_real_escape_string($connect, $data[3]);
$student_last_name = mysqli_real_escape_string($connect, $data[4]);
$student_phone_number = mysqli_real_escape_string($connect, $data[5]);
$student_gender = mysqli_real_escape_string($connect, $data[6]);
$original_back_school = mysqli_real_escape_string($connect, $data[7]);
$original_end_time = mysqli_real_escape_string($connect, $data[8]);
$original_class = mysqli_real_escape_string($connect, $data[9]);
$class_Halom= mysqli_real_escape_string($connect, $data[10]);
$parent_id = mysqli_real_escape_string($connect, $data[11]);
$teacher_id = mysqli_real_escape_string($connect, $data[12]);
$query = "INSERT INTO `student`(`student_id`, `student_login`, `student_password`, `student_first_name`, `student_last_name`, `student_phone_number`, `student_gender`, `original_back_school`, `original_end_time`, `original_class`, `class_Halom`, `parent_id`, `teacher_id`) VALUES ($student_id, '$student_login','$student_password','$student_first_name','$student_last_name', '$student_phone_number','$student_gender','$original_back_school',' $original_end_time','$original_class','$class_Halom','$parent_id','$teacher_id') ";
mysqli_query($connect, $query);
}
fclose($handle);
header("location: index.php?updation=1");
}
else
{
$message = '<label class="text-danger">Please Select CSV File only</label>';
}
}
else
{
$message = '<label class="text-danger">Please Select File</label>';
}
}
if(isset($_GET["updation"]))
{
$message = '<label class="text-success">Updation Done</label>';
}
$query = "SELECT * FROM student";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload Mysql Database through Upload CSV File using PHP</title>
<script src="../jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="../bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h2 align="center">Update Mysql Database through Upload CSV File using PHP</h2>
<br />
<form method="post" enctype='multipart/form-data'>
<p><label>Please Select File(Only CSV Formate)</label>
<input type="file" name="product_file" /></p>
<br />
<input type="submit" name="upload" class="btn btn-info" value="Upload" />
</form>
<br />
<?php echo $message; ?>
<h3 align="center">Student table</h3>
<br />
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>student_id</th>
<th>student_login</th>
<th>student_password</th>
<th>student_first_name</th>
<th>student_last_name</th>
<th>student_phone_number</th>
<th>student_gender</th>
<th>original_back_school</th>
<th>original_end_time</th>
<th>original_class</th>
<th>class_Halom</th>
<th>parent_id</th>
<th>teacher_id</th>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>'.$row["student_id"].'</td>
<td>'.$row["student_login"].'</td>
<td>'.$row["student_password"].'</td>
<td>'.$row["student_first_name"].'</td>
<td>'.$row["student_last_name"].'</td>
<td>'.$row["student_phone_number"].'</td>
<td>'.$row["student_gender"].'</td>
<td>'.$row["original_back_school"].'</td>
<td>'.$row["original_end_time"].'</td>
<td>'.$row["original_class"].'</td>
<td>'.$row["student_login"].'</td>
<td>'.$row["class_Halom"].'</td>
<td>'.$row["parent_id"].'</td>
<td>'.$row["teacher_id"].'</td>
</tr>
';
}
?>
</table>
</div>
</div>
</body>
</html>
and this is the student table from my database
..............

There is an error in the line
$query = "INSERT INTO `student`(`student_id`, `student_login`, `student_password`, `student_first_name`, `student_last_name`, `student_phone_number`, `student_gender`, `original_back_school`, `original_end_time`, `original_class`, `class_Halom`, `parent_id`, `teacher_id`) VALUES ($student_id, '$student_login','$student_password','$student_first_name','$student_last_name', '$student_phone_number','$student_gender','$original_back_school',' $original_end_time','$original_class','$class_Halom','$parent_id','$teacher_id') ";
$student_id is not written within ' '
It should be like '$student_id'
So actual code will be
$query = "INSERT INTO `student`(`student_id`, `student_login`, `student_password`, `student_first_name`, `student_last_name`, `student_phone_number`, `student_gender`, `original_back_school`, `original_end_time`, `original_class`, `class_Halom`, `parent_id`, `teacher_id`) VALUES ('$student_id', '$student_login','$student_password','$student_first_name','$student_last_name', '$student_phone_number','$student_gender','$original_back_school',' $original_end_time','$original_class','$class_Halom','$parent_id','$teacher_id') ";
This will solve your issue.

Since you're using .csv files, you can tell PHP that your separator is a semicolon.
<?php
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
?>
To search each value of your file, you can use a strategy like this:
<?php
$row = 0;
if (($handle = fopen("c:\\temp\\test.csv", "r")) !== FALSE)
{
//Searching line by line of the file
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$num = count($data);
$row++;
//Searching column by column of the current line
for ($col = 0; $col < $num; $col++)
{
//Here you can use the desired values
switch ($col) {
case 0:
$student_id = mysqli_real_escape_string($connect,$data[$col]);
break;
case 1:
$student_login = mysqli_real_escape_string($connect,$data[$col]);
break;
case 2:
$student_password = mysqli_real_escape_string($connect,$data[$col]);
break;
case 3:
$student_first_name = mysqli_real_escape_string($connect,$data[$col]);
break;
case 4:
$student_last_name = mysqli_real_escape_string($connect,$data[$col]);
break;
case 5:
$student_phone_number = mysqli_real_escape_string($connect,$data[$col]);
break;
case 6:
$student_gender = mysqli_real_escape_string($connect,$data[$col]);
break;
case 7:
$original_back_school = mysqli_real_escape_string($connect,$data[$col]);
break;
case 8:
$original_end_time = mysqli_real_escape_string($connect,$data[$col]);
break;
case 9:
$original_class = mysqli_real_escape_string($connect,$data[$col]);
break;
case 10:
$class_Halom = mysqli_real_escape_string($connect,$data[$col]);
break;
case 11:
$parent_id = mysqli_real_escape_string($connect,$data[$col]);
break;
case 12:
$teacher_id = mysqli_real_escape_string($connect,$data[$col]);
break;
}//end switch
}//endfor (columns of each line)
//If your file has a header and you wish to skip it, you can do something like this:
//if ($row > 1) { //create your query and execute it... }
$query = "INSERT INTO `student`(`student_id`, `student_login`, `student_password`, `student_first_name`, `student_last_name`, `student_phone_number`, `student_gender`, `original_back_school`, `original_end_time`, `original_class`, `class_Halom`, `parent_id`,`teacher_id`) VALUES ";
$query.= "($student_id, '$student_login','$student_password','$student_first_name','$student_last_name','$student_phone_number','$student_gender','$original_back_school','$original_end_time','$original_class','$class_Halom', $parent_id, $teacher_id) ";
mysqli_query($connect, $query);
//}
}
fclose($handle);
}
?>

Related

Insert into database using excel from database start from col 2

I`m trying to insert data into a database, from an excel file but starting from column 2 because the first column is being used for the name of the row in the table.
This is my form to input the file, this code reads from the first column, I want to start reading from column 2.
<h2>Import Excel File into MySQL Database using PHP</h2>
<div class="outer-container">
<form action="import.php" method="post"
name="frmExcelImport" id="frmExcelImport" enctype="multipart/form-data">
<div>
<label>Choose Excel
File</label> <input type="file" name="file"
id="file" accept=".xls,.xlsx">
<button type="submit" id="submit" name="import"
class="btn-submit">Import</button>
</div>
</form>
</div>
<div id="response" class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?></div>
and this is the action file:
<?php
include 'koneksi/koneksi.php';
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"]))
{
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row )
{
$id_koperasi = "";
if(isset($Row[0])) {
$id_koperasi = mysqli_real_escape_string($con,$Row[0]);
}
$nama_koperasi = "";
if(isset($Row[1])) {
$nama_koperasi = mysqli_real_escape_string($con,$Row[1]);
}
$alamat = "";
if(isset($Row[2])) {
$alamat = mysqli_real_escape_string($con,$Row[2]);
}
$telp = "";
if(isset($Row[3])) {
$telp = mysqli_real_escape_string($con,$Row[3]);
}
$hp = "";
if(isset($Row[4])) {
$hp = mysqli_real_escape_string($con,$Row[4]);
}
$nama_cp = "";
if(isset($Row[5])) {
$nama_cp = mysqli_real_escape_string($con,$Row[5]);
}
$email = "";
if(isset($Row[6])) {
$email = mysqli_real_escape_string($con,$Row[6]);
}
$tanggal_fu = "";
if(isset($Row[7])) {
$tanggal_fu = mysqli_real_escape_string($con,$Row[7]);
}
$ket_fu = "";
if(isset($Row[8])) {
$ket_fu = mysqli_real_escape_string($con,$Row[8]);
}
$hasil_pembahasan = "";
if(isset($Row[9])) {
$hasil_pembahasan = mysqli_real_escape_string($con,$Row[9]);
}
$status = "";
if(isset($Row[10])) {
$status = mysqli_real_escape_string($con,$Row[10]);
}
$provinsi = "";
if(isset($Row[11])) {
$provinsi = mysqli_real_escape_string($con,$Row[11]);
}
$kota = "";
if(isset($Row[12])) {
$kota = mysqli_real_escape_string($con,$Row[12]);
}
$kec = "";
if(isset($Row[13])) {
$kec = mysqli_real_escape_string($con,$Row[13]);
}
$kel = "";
if(isset($Row[14])) {
$kel = mysqli_real_escape_string($con,$Row[14]);
}
$rt = "";
if(isset($Row[15])) {
$rt = mysqli_real_escape_string($con,$Row[15]);
}
$rw = "";
if(isset($Row[16])) {
$rw = mysqli_real_escape_string($con,$Row[16]);
}
$jln = "";
if(isset($Row[17])) {
$jln = mysqli_real_escape_string($con,$Row[17]);
}
$kodep = "";
if(isset($Row[18])) {
$kodep = mysqli_real_escape_string($con,$Row[18]);
}
if (!empty($id_koperasi) || !empty($nama_koperasi) || !empty($alamat) || !empty($telp) || !empty($hp) || !empty($nama_cp) || !empty($email) || !empty($tanggal_fu) || !empty($ket_fu) || !empty($hasil_pembahasan) || !empty($status) || !empty($provinsi) || !empty($kota) || !empty($kec) || !empty($kel) || !empty($rt) || !empty($rw) || !empty($jln) || !empty($kodep) ) {
$query = "INSERT INTO t_koperasi(id,id_koperasi,nama_koperasi,alamat,telp,hp,nama_cp,email,tanggal_fu,ket_fu,hasil_pembahasan,status,provinsi,kota,kec,kel,rt,rw,jln,kodep) VALUES ('',
'$id_koperasi',
'$nama_koperasi',
'$alamat',
'$telp',
'$hp',
'$nama_cp',
'$email',
'$tanggal_fu',
'$ket_fu',
'$hasil_pembahasan',
'$status',
'$provinsi',
'$kota',
'$kec',
'$kel',
'$rt',
'$rw',
'$jln',
'$kodep')" or die(mysqli_error($con));
;
$result = mysqli_query($con, $query);
if (! empty($result)) {
$type = "success";
$message = "SUKSES";
} else {
$type = "error";
$message = "Problem in Importing Excel Data";
}
}
}
}
}
else
{
$type = "error";
$message = "Invalid File Type. Upload Excel File.";
}
}
include 'views/v_import.php'
?>
I already tried to put $col = 1 but it still wont work, I tried using the for=i but it still will not work.
a possible solution with an extra counter
$Reader->ChangeSheet($i);
$number = 0;
foreach ($Reader as $Row )
{
if ($number!=0) {
......
}
$number++;
}

UTF8 in php mysql

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>

Reading csv to insert in mysql. fill empty columns with previous line

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

How to tabulate data present in a sqlite database with PHP

Hi I wrote down the following PHP script to show data written in sqlite database in form a HTML table. When I open the page I only see the heading Control Panel. I have saved it as index.php under my servers root directory.
<html>
<head>
<title>Switch and Status Report</title>
</head>
<body>
<h1>Control Panel</h1>
<table border="1" style="width:100%">
<?php
$dbhandle = sqlite_open('db/pj.db', 0666, $error);
if (!$dbhandle) die ($error);
$query = "SELECT * FROM state";
$result = sqlite_query($dbhandle, $query);
if (!$result) die("Cannot execute query.");
$array = sqlite_fetch_all($result, SQLITE_NUM);
echo($array);
for ($x = 0; $x <= 6; $x++) {
$curarr = $array[$x];
$curpin = $curarr[0];
$curname = $curarr[1];
$curstate = $curarr[2];
$curdep = $curarr[3];
$textst = "";
$linkst = "";
$textdep = "";
$linkdep = "";
if($curstate==(0)){
$textst = "Turn On";
$linkst = "statechange.php";
}
elseif($curstate==(1)){
$textst = "Turn Off";
$linkst = "statechange.php";
}
if($curdep==(0)){
$textst = "Make Motion Dependent";
$linkst = "motionchange.php";
}
elseif($curstate==(1)){
$textst = "Make Motion Independent";
$linkst = "statechange.php";
}
echo("<tr>");
echo("<td>$curpin</td>");
echo("<td>$curname</td>");
echo("<td><a href='$linkst'>$textst</a></td>");
echo("<td><a href='$linkdep'>$textdep</a></td>");
echo("</tr>");
sqlite_close($dbhandle);
}
?>
</table>
</body>
</html>
Please Troubleshoot and help me. Thanks in advance.
You are missing on the $curarr part. On line 18 above see that you've omitted the $ sign. Its generating an error.
<html>
<head>
<title>Switch and Status Report</title>
</head>
<body>
<h1>Control Panel</h1>
<table border="1" style="width:100%">
<?php
$dbhandle = sqlite_open('db/pj.db', 0666, $error);
if (!$dbhandle) die ($error);
$query = "SELECT * FROM state";
$result = sqlite_query($dbhandle, $query);
if (!$result) die("Cannot execute query.");
$array = sqlite_fetch_all($result, SQLITE_NUM);
echo($array);
for ($x = 0; $x <= 6; $x++) {
$curarr = $array[$x];
$curpin = $curarr[0];
$curname = $curarr[1];
$curstate = $curarr[2];
$curdep = $curarr[3];
$textst = "";
$linkst = "";
$textdep = "";
$linkdep = "";
if($curstate==(0)){
$textst = "Turn On";
$linkst = "statechange.php";
}
elseif($curstate==(1)){
$textst = "Turn Off";
$linkst = "statechange.php";
}
if($curdep==(0)){
$textst = "Make Motion Dependent";
$linkst = "motionchange.php";
}
elseif($curstate==(1)){
$textst = "Make Motion Independent";
$linkst = "statechange.php";
}
echo("<tr>");
echo("<td>$curpin</td>");
echo("<td>$curname</td>");
echo("<td><a href='$linkst'>$textst</a></td>");
echo("<td><a href='$linkdep'>$textdep</a></td>");
echo("</tr>");
sqlite_close($dbhandle);
}
?>
</table>
</body>

Creating a CSV Upload to Mysql

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.

Categories