It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to use a csv file to update the mysql scv table. how to code ? I have no experiece doing this job.
<p>please select a scv file to upload</p>
<form action="index.php" method="post">
<input type="file" name="scv" />
<input type="submit" value="submit" />
</form>
<?php
mysql_connect('localhost','root','admin');
mysql_select_db('linjuming');
// how to upload a scv file and insert or update the "csv" table?
?>
Your upload file:
<form action="upload_target.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
Your upload_target.php
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if ($ext == "csv" && $_FILES["file"]["error"] == 0)
{
$target = "upload/" . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], $target);
if (($handle = fopen($target, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
print_r($data);
}
fclose($handle);
}
}
Very basic and with very few checks / validations. The print_r($data) contains one line of your csv that you can now insert in your database.
However, I would recommend using PDO or MySQLi for that task, since the mysql functions of PHP will be deprecated in the future.
There's several parts of this:
First, your form MUST have the enctype set, as follows:
<form enctype="multipart/form-data" action="index.php" method="post">
Otherwise, it will not accept file uploads.
Once you've done that, then you can access the file using the $_FILES variable. After the file has been uploaded, then you can access it like so:
if (isset($_FILES["scv"])) {
$file = $_FILES["scv"];
$file_name = $file["name"];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
if ($ext!="CSV" && $ext!="TXT") {
die('The file must be csv or txt format.');
}
$saveto_path_and_name = '/path/to/file.csv'; // Where you want to save the file
move_uploaded_file($file["tmp_name"], $saveto_path_and_name);
}
Once you've saved the file, you then can open it and import it. That's not trivial to do, but here's some primer code:
// Open the file for reading
$handle = #fopen($saveto_path_and_name, "r") or die(__("Unable to open uploaded file!", "inventory"));
// Grab the first row to do some checks
$row = fgets($inv_file, 4096);
// See if it's comma or tab delimited
if (stripos($inv_row, "\t")) {
$sep = "\t";
} else {
$sep = ",";
}
while ( ! feof($handle)) {
$rowcount = 0;
// Get the individual fields
$inv_fields = explode($sep, $inv_row);
$fields = array();
// Iterate through the fields to do any sanitization, etc.
foreach ($inv_fields as $field) {
// Highly recommended to sanitize the variable $field here....
$fields[] = $field;
$rowcount++;
}
// This is where you would write your query statement to insert the data
// This is just EXAMPLE code. Use the DB access of your choice (PDO, MySQLi)
$sql = vsprintf('INSERT INTO `table` (`column`, `column2`, ...) VALUES (%s, %d, ...)', $fields);
// Get the next row of data from the file
$row = fgets($inv_file, 4096);
}
Related
Can someone figure out the logic on how to upload an excel sheet into a web server and to compare it with already existing data.
Say I have some data in my database which looks similar to an excel sheet arrangement. Now i need to upload an excel sheet and compare it with DB and to do some kind of sorting and all. And finally I need to import the final result as an excel and download it. So at the same time i need to remove the uploaded file also.
NB: i dont need the code.. i need someone to explain me the concept so that i can try coding it myself
Check this :
<form action="" enctype="multipart/form-data" method="post>
<input type="file" name="txtFile" id="eskal" /></br>
<input type="submit" name="Import" value="Update Database" /> </b>
</form>
<?php
if(isset($_POST["Import"]))
{
$host="localhost"; // Host name.
$db_user="root";
$db_password="";
$db='test'; // Database name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
echo $filename=$_FILES["file"]["tmp_name"];
//echo $ext=substr($filename,strrpos($filename,"."),(strlen($filename)-strrpos($filename,".")));
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
// You can compare your data inside this while loop as well as above the while loop.
print_r($emapData);
$sql = "INSERT into import(name,address,email,password) values('$emapData[0]','$emapData[1]')";
mysql_query($sql);
}
fclose($file);
echo "CSV File has been successfully Imported";
}
else
echo "Invalid File:Please Upload CSV File";
}
?>
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
My code is below, and i am not understanding that what problem is in this code, because my data is not saving in mysql db table. Is anyone tell me that what problem is in my code?
===========================================================================================
<?php
$con = mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('csv_data',$con) or die(mysql_error());
$data = array();
if(isset($_FILES['submit'])){
if($FILES['csv_file']['size'] > 0){
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file,"r");
while($data = fgetcsv($handle, 134217728, ',')){
$query = "INSERT INTO data(url) VALUES ('".$data[0]."')";
mysql_query($query) or die(mysql_error());
echo "File Uploaded.";
}
}
}
?>
<body>
<form name="frm" action="save_csv_in_mysql_table.php" method="post">
<input type="file" name="csv_file" value="Upload Csv File"/>
<input type="submit" name="submit" value="Upload CSV File"/>
</form>
</body>
You need use if(isset($_POST['submit'])){
PHP:
$con = mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('csv_data',$con) or die(mysql_error());
$data = array();
if(isset($_POST['submit'])){
if($FILES['csv_file']['size'] > 0){
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file,"r");
while($data = fgetcsv($handle, 134217728, ',')){
$query = "INSERT INTO data(url) VALUES ('".$data[0]."')";
mysql_query($query) or die(mysql_error());
echo "File Uploaded.";
}
}
}
What is $_FILES['submit']? I think, you have not this index.
Try to add in the beginning
print_r($_POST);
print_r($_FILES);
and than create a normal statement.
For example:
if (isset($_FILES['csv_file'])) {do something}
At the second: don't use INSERT with mysql_query. Read about PDO, it's safe and comfort. There is a vulnerability in your code (SQL Injection).
You have built your form incorrectly, so NO FILE IS BEING UPLOADED:
<form enctype="multipart/form-data" name="frm" action="save_csv_in_mysql_table.php" method="post" >
^^^^^^^^^^^^^^^^^^^^^^^^^^^^--missing
You then failed to check if an upload was actually successful and simply blundered onwards blindly:
if (isset($_FILES['csv_file']['error']) && ($_FILES['csv_file']['error'] !== UPLOAD_ERR_OK)) {
die("Upload failed with error code#: " . $_FILES['csv_file']['error']);
}
You then blindly try to slurp data from this file and insert that data directly into your query string, also leaving you wide open to SQL injection attacks.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
i am trying to upload image through following code.
although my if condition is executing as shown below but image is not moving to the specified path given by me. my code is below.
here is my html code
<form enctype="multipart/form-data" action="catcher.php" method="POST">
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
and here is my php code
<?php
$uploaddir = '/xampp/project/';
echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploaddir)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
can any body point out whats wrong with my code i mean why the image i am trying to upload is not moving to the specified path,,
move_uploaded_file() requires the second parameter to be destination file, not directory.
You could do:
$filename = $uploaddir . basename($_FILES['userfile']['tmp_name']);
if( move_uploaded_file($_FILES['userfile']['tmp_name'], $filename)){
// ...
But there is good chance that multiple users will try to upload files with the same name, so I strictly recommend to handle this possibility.
$folder = "../images/stories/";
$result = move_uploaded_file($_FILES['excel']['tmp_name'], $folder.$filename);
Give destination folder name. (In above code, $folder is destination path variable)
You can see detail on this function:
function upload($name,$tmp_name){
$fileextarr=explode('.',$name);
$fileextarr[0];
$fileext=$fileextarr[count($fileextarr)-1];
$fpath = "../images/stories/lab_excel/";
$filename = ereg_replace(" ","_",$fileextarr[0]).'.'.$fileext;
//You can use restriction on file extensions also. (not necessary)
if($fileext=="xls" || $fileext=="xlsx" || $fileext=="doc"|| $fileext=="docx" || $fileext=="jpeg" || $fileext=="png" || $fileext=="gif" || $fileext=="tiff" || $fileext=="bmp" || $fileext=="jpg")
{
$uploadedfile = $filename;
}
//Here is the use of destination path:
$folder = "../images/stories/lab_excel/";
$result = move_uploaded_file($_FILES['excel']['tmp_name'], $folder.$filename);
/*echo $folder.$_FILES['excel']['name'];
die();*/
if($result){
$msg="File Uploaded Successfully";
return $folder.$filename;
}
else
{
return false;
}
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
On my website, I have an upload story feature with a user written title and story. It uploads it as a text file in a directory. Is there a way to list the content of these files using php or anything? Also, I'd like to only show like 200 chars of the story, and have a 'show full story' button, that would show the full story (I'll use jQuery for this).
Thanks!
$dataArray = array();
//Number of chars for the string
$num = 200;
//Check if DIR exists
if ($handle = opendir('.')) {
//Loop over the directory
while (false !== ($file = readdir($handle))) {
//Strip out the . and .. files
if ($file != "." && $entry != "..") {
$dataArray[] = array();
//Store file contents
$filecontent = file_get_contents($file);
//Split the content and store in array
$length = strlen($filecontent);
$dataArray[] = array(substr($filecontent, 0, $num), substr($filecontent, $num, $length ));
}
}
//close the dir
closedir($handle);
}
With this you get an array with all the content of your .txt files, splittet into 2 Strings, one with 200 chars the other with the rest.
The string with 200 length is $dataArray[x][0] and the other is $dataArray[x][1].
Now you can use this in HTML:
<?php foreach($dataArray as $data) { ?>
<div class="visible">
<?php echo $data[0]; ?>
</div>
<div class="hidden">
<?php echo $data[1]; ?>
</div>
<?php } ?>
in php.net:
to open a directory:
opendir() http://php.net/manual/en/function.opendir.php
$dir = opendir('/path/to/files');
to read the directory (you can loop):
readdir() http://www.php.net/manual/en/function.readdir.php
while (false !== ($file= readdir($dir))) {
//$file has the filename
}
to get the content of a file:
file_get_contents() http://php.net/manual/es/function.file-get-contents.php
$content=file_get_contents($file);
I really want to know how am I gonna get the full filepath when I upload a file in PHP?
Here's my my problem...
I am importing a csv file in PHP. Uploading a file isn't a problem but the function used to import csv files which is fgetcsv() requires fopen. fopen is the one giving me a headache because it requires an exact filepath which means that the file should be in the same directory with the php file. What if the user gets a file from a different directory.
Here's my codes:
index.php:
<form action="csv_to_database.php" method="POST" enctype="multipart/form-data">
<input type="file" name="csv_file" />
<input type="submit" name="upload" value="Upload" />
</form>
csv_import.php:
<?php
if ($_FILES['csv_file']['error'] > 0) {
echo "Error: " . $_FILES['csv_file']['error'] . "<br />";
}else{
if (($handle = fopen($_FILES['csv_file']['name'], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
for ($c=0; $c < count($data) ; $c++) {
echo $data[$c] . " ";
}
echo "<br />";
}
fclose($handle);
}
}
?>
fopen here can only get the filename which is passed by the variable $_FILES['csv_file']['name']. I was trying to get any functions to get the full filepath for $_FILES in the internet but can't find any.
I am very new to web development so pls be patient. Pls answer as simple as possible... Pls help...
The ['name'] refers to the original filename on the users computer. That's no use to you, in particular because it might be empty. (Or it can contain fake values, causing a directory traversal exploit. So, just avoid it.)
You need to use the ['tmp_name'] which is a server-absolute path like /tmp/upload85728 that can be used for fopen() or move_uploaded_file().
I was able to successfully imported csv file and stored it in the mysql database.
Here are the the codes (actually its almost the same as my question with some slight changes with great effect):
index.php:
<form action="csv_import.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="csv_file" />
<input type="submit" name="upload" value="Upload" />
</form>
csv_import.php:
<?php
if ($_FILES['csv_file']['error'] > 0) {
echo "Error: " . $_FILES['csv_file']['error'] . "<br />";
}else{
if (($handle = fopen($_FILES['csv_file']['tmp_name'], "r")) !== FALSE) {
$dbconn = mysql_connect("localhost", "root", "") or die("Couldn't connect to server!");
mysql_select_db("csv_test") or die("Couldn't find database!");
$ctr = 1; // used to exclude the CSV header
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($ctr > 1) mysql_query("INSERT INTO ninja_exer (name, village, country) VALUES ('$data[1]', '$data[2]', '$data[3]')");
else $ctr++;
}
fclose($handle);
}
}
?>
you need to define a path into your config file or wherever you want to use and then that variable whatever you define, you can use in you project.
i.e: define('FILE_UPLOADED_PATH','folder1/folder2/so on');
so after the put this code your full filepath would be-
FILE_UPLOADED_PATH.$_FILES['csv_file']['name'];
you can use above code as example.
Thanks.