How to upload csv file using php into mysql database correctly?
I have a column (uploaded, column name) in phpmyadmin, in this column will store the uploaded csv file.
I have a little script of uploading csv file into mysql database, but I'm getting some error "404: File Not Found" after I clicked the submit button and the csv file is not saving in the database.
Here the php file with html:
<?php
include "dbase.php"; //Connect to Database
$deleterecords = "TRUNCATE TABLE contracts"; //empty the table of its current records
mysql_query($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
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into contracts(uploaded) values('$data[0],$data[1]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
echo "Import done";
//view upload form
}else {
echo "Upload new csv by browsing to file and clicking on Upload<br />\n";
echo "<form enctype='multipart/form-data' action='upload.php' method='post'>";
echo "File name to import:<br />\n";
echo "<input size='50' type='file' name='filename'><br />\n";
echo "<input type='submit' name='submit' value='Upload'></form>";
}
?>
Database connection:
<?
$filename=$_POST['filename'];
$db=mysql_connect('localhost', 'username', 'password', '3306')
or die(mysql_error());
if(!$db)
die("no db");
if(!mysql_select_db("databasename",$db))
die("No database selected.");
?>