Uploading a csv and importing the data in MySQL - php

ok all I want to do is give the user a simple form where they can upload a CSV file which contains fares. The data should then upload into the database.
Here's the code...
<?php
require_once('includes/connection.php');
if(isset($_POST['submit']))
{
$filename=$_POST['filename'];
$handle = fopen("$filename", "r");
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE)
{
$import="INSERT into fares_usa(cruise_id, active, type, category, placement, deck, fare, offered, status, sortorder) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]')";
mysql_query($import, $connection) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
else
{
print "<form enctype='multipart/form-data' action='fileupload.php' method='POST'>";
print "Select file to import:";
print "<input type='file' name='filename' size='20'>";
print "<input type='submit' name='submit' value='submit'></form>";
}
?>
Any help is greatly appreciated !
Thanks
Rich :)

You seem to be using $_POST and not $_FILES
<?php
require_once('includes/connection.php');
if(isset($_POST['submit']))
{
$filename=$_FILES['filename']['tmp_name'];
$handle = fopen("$filename", "r");
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE)
{
$import="INSERT into fares_usa(cruise_id, active, type, category, placement, deck, fare, offered, status, sortorder)
values('".mysql_real_escape_string($data[0])."',
'".mysql_real_escape_string($data[1])."',
'".mysql_real_escape_string($data[2])."',
'".mysql_real_escape_string($data[3])."',
'".mysql_real_escape_string($data[4])."',
'".mysql_real_escape_string($data[5])."',
'".mysql_real_escape_string($data[6])."',
'".mysql_real_escape_string($data[7])."',
'".mysql_real_escape_string($data[8])."',
'".mysql_real_escape_string($data[9])."')";
mysql_query($import, $connection) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
else
{
print "<form enctype='multipart/form-data' action='fileupload.php' method='POST'>";
print "Select file to import:";
print "<input type='file' name='filename' size='20'>";
print "<input type='submit' name='submit' value='submit'></form>";
}
?>
Also added mysql_real_escape_string to escape your input before adding it to the database. This is the bare minimum "cleaning" that you should be doing for user input.

Related

get specific row from csv file when importing into phpmysqladmin

I'm new in here, I'm trying to get a Specific rows for a calendar csv file and import to phpmysql database but could not actually get it, hoping someone can hep me
this is my csv file
this is my database look like, i want to get row 4,6,8...so on from csv file and import to table:calendar, column:day and get row 3,5,7...to the same table but column:date
And this is my code
<?php
include "dbFunctions.php"; //Connect to Database
$deleterecords = "TRUNCATE TABLE calendar"; //empty the table of its current records
mysqli_query($link, $deleterecords);
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." Uploaded Successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
//exclude the first row title
$row = 1;
if(($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($i=0; $i<=38; $i++){
if($firstRow) { $firstRow = false; }
else {
$import="INSERT into class(day, date)
values('$data[0]','$data[1]')";
mysqli_query($link, $import) or die(mysqli_error($link));
}
echo $data[$i] . "<br />\n";
}}
fclose($handle);
}
//view upload form
}else {
print "Upload csv file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='uploadCalendar.php' method='post'>";
print "csv File to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
Since the patterns are odd and even rows.
$row = 0;
$i = 0;
$container = array();
if(($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row > 2) {
if ($row % 2 == 0) {
$i = $i - 6;
$v = 'day';
} else {
$v = 'date';
}
foreach ($data as $column) {
$container[$i][$v] = $column;
$i++;
}
}
$row++;
}
fclose($handle);
}
foreach ($container as $value) {
$import="INSERT into class(day, date)
values('".$value['day']."','".$value['date']."')";
mysqli_query($link, $import) or die(mysqli_error($link));
}
The $container should contain the date paired to the day. Like,
$container = [['day' => 'W1D1', 'date' => '19-Oct'], ['day' => 'W1D2', 'date' => '20-Oct']];
And you can use loop to insert into database.

How to export .csv file with merge cells into mysql using php?

In my .csv file there is a data like this :
id | code | name
1mca | 3ca1523 | c
| 3ca1524 | cpp
| 3ca1525 | java
3mca | 3ca1621 | php
| 3ca1624 | ooad
my code to export this into mysql :
<?php
$db = mysqli_connect("localhost", "root", "") or die("could not connect");
if(!$db)
die("no db");
if(!mysqli_select_db($db,"phptester"))
die("No database selected.");
if(isset($_POST['submit']))
{
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES["file"]["name"]);
echo $uploadfile;
if (move_uploaded_file($_FILES["file"]["tmp_name"], $uploadfile))
{
$handle = fopen("$uploadfile", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$import="INSERT into subject(sem,code,name) values('$data[0]','$data[1]','$data[2]')";
mysqli_query($db,$import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
}
else
{
print "<form action='index.php' method='post' enctype='multipart/form-data'>";
print "Choose file to import:<br><br>";
print "<input type='file' name='file' id='file'><br><br>";
print "<input type='submit' name='submit' value='extract'></form>";
}
?>
So, there is a merged column in a csv file, when i run this script first record is inserted like this 1mca,3ca1524,c and next record like this ,3ca1525,cpp instead i want in the second record there should be 1mca inserted in the first field how to achieve this?
on line where is:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
try to replace for:
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE)
Third parameter of fgetcsv is delimiter for fetching data from csv. you have "," instead of "|"

Insert with php in mysql from CSV if not exists

I got a problem and could't find a solution for me.
I want to insert with a php script in my mysql database from a csv file.
The database got a primary key, which is created automatically on every insert.
The csv file grows with time, but the existed date should not be inserted again! I could not check the primary key in this case, because it is generated on every insert.
This is my file so far:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT INTO xt_products(
products_owner,
products_quantity,
products_shippingtime,
products_model,
products_model_original,
products_price,
products_tax_class_id
) VALUES (
'$data[0]',
'$data[1]',
'$data[2]',
'$data[3]',
'wayne_$data[4]',
'$data[5]',
'$data[6]'
)";
mysql_query($import) or die (mysql_error());
}
I know about where exists or if exists bgin end, but I could not get it to work.
Edit: Forgot to mention it, it should check, whether the products_model is already in the database. That would be the $data[3] field there
You just have to add the duplicate statement
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT INTO xt_products(
products_owner,
products_quantity,
products_shippingtime,
products_model,
products_model_original,
products_price,
products_tax_class_id
) VALUES (
'$data[0]',
'$data[1]',
'$data[2]',
'$data[3]',
'$data[4]',
'$data[5]',
'$data[6]'
)
ON DUPLICATE KEY UPDATE products_owner='$data[0]'
";
mysql_query($import) or die (mysql_error());
}
<?php
include ("config.php"); //Connect to Database
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into table(something,something,something,something,something,something,something) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
//view upload form
}else {
print "Upload new csv by browsing to file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='import.php' method='post'>";
print "File name to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
config.php
<?php
$db = mysql_connect('localhost', 'user', 'pass') or die("Could not connect.");
if(!$db)
die("no db");
if(!mysql_select_db("database",$db))
die("No database selected.");
?>

To Insert Checkbox Values into Database

Currently I am doing a project in php for uploading CSV file and to insert data into database. Before Inserting I need to display the data in checkboxes and to insert the values that are checked.
With this code after uploading it displays data with checkbox but on clicking the checkbox the values are not inserting into database.
if(isset($_POST['upload']))
{
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
}
$handle = fopen($_FILES['filename']['tmp_name'], "r");
echo("<table border='1'>");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
echo("<tr>\r\n");
foreach ($data as $index=>$val)
{
echo("\t<td><input type='checkbox' name='chk1[]' value='$val'>$val</td>\r\n");
}
echo("</tr>\r\n");
}
echo("</table>");
echo("<td><input type='submit' name='insert' id='insert' value='Submit' /></td>");
fclose($handle);
}
For Inserting the selected data into database I am using this code.
if(isset($_POST['insert']))
{
for($i=0;$i < sizeof($checkbox1);$i++)
{
$query = "INSERT INTO uploadmail (name,email) VALUES ('$name','".$checkbox1[$i]."')";
echo $query;
$result = mysql_query($query);
}
}
After clicking checkboxes when I click Submit button it is not doing any action.So Please give me any suggestions.
THANKS IN ADVANCE.
Your table closed before the form submit. And please maintain the table structure if you are using form in a table. Close all input fields in table's td followed by "tr".
And here its understood that you assigned $checkbox1 = $_POST['chk1'];

How to check before upload a CSV file to MySQL db if user has selected one

I have simple script that uploads CSV files to a MySQL database. It works ok but if user misses selecting some CSV file to upload and pushes the UPLOAD button, the script tries to insert thousand of 0 lines in the data base.
I wonder if there is a way to check befoere upload file if user has allready selected FILE.
Here is my code:
<?php
include("conection.php"); //Connect to Database
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<br><center><p>" . " ". $_FILES['filename']['name'] ." " . "</p></center>";
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$count = 0; //skip first line of the CSV file
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
if($count) //skip first line of the CSV file
{
$import="INSERT into PAX (name,surname,group) VALUES('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
}
$count++;
}
fclose($handle);
print "<br><center><p>UPLOADED </p></center> ";
print "<br> ";
print "<center><a href='index.php'><button>HOME</button</a></center> ";
//view upload form
}else {
print "<center><br><p><b>UPLOAD</b> </p>\n";
print "<center><br>Select the file for Upload \n";
print "<form enctype='multipart/form-data' action='upload.php' method='post'>";
print "<center><input size='50' type='file' name='filename'><br />\n";
print "<br>";
print "<input type='submit' name='submit' value='UPLOAD'></form>";
}
?>
Hard to say definitively with your code as it is presented & without seeing the original data, but I believe simply setting a conditional that checks $data is enough to prevent the issue you are seeing:
So this line:
if ($count) //skip first line of the CSV file {
Changes to this:
if ($count && !empty($data)) //skip first line of the CSV file {
And here is your code adjusted and indents cleaned up for readability. EDIT And I have edited it so there is now a $SUCCESS_SUBMIT variable. That way if the submission is successful & that is true or false you can act on it.
include("conection.php"); //Connect to Database
$SUCCESS_SUBMIT = false;
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<br><center><p>" . " ". $_FILES['filename']['name'] ." " . "</p></center>";
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$count = 0; //skip first line of the CSV file
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
if ($count && !empty($data)) //skip first line of the CSV file {
$import = "INSERT into PAX (name,surname,group) VALUES('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
$SUCCESS_SUBMIT = true;
}
$count++;
}
fclose($handle);
}
if ($SUCCESS_SUBMIT) {
print "<br><center><p>UPLOADED </p></center> ";
print "<br> ";
print "<center><a href='index.php'><button>HOME</button</a></center> ";
}
else {
print "<center><br><p><b>UPLOAD</b> </p>\n";
print "<center><br>Select the file for Upload \n";
print "<form enctype='multipart/form-data' action='upload.php' method='post'>";
print "<center><input size='50' type='file' name='filename'><br />\n";
print "<br>";
print "<input type='submit' name='submit' value='UPLOAD'></form>";
}
"There is a way to show user if hasnt selected any csv file give a message file "please select file" or something like this"
you could use javascript to have a message, if not file selected:
print "<form enctype='multipart/form-data' action='upload.php'
onsubmit='return validateUpload();' name='formUpload'
method='post'>";
print "<center><input size='50' type='file' name='filename'><br />\n";
print "<br>";
print "<input type='submit' name='submit' value='UPLOAD'></form>";
}
?>
<script type="text/javascript" >
function validateUpload()
{
var fName = document.forms["formUpload"]["filename"].value;
if (fName==null || fName=="")
{
alert("Please select file !");
return false;
}
}
</script>

Categories