Data is not saving in mysql db [closed] - php

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.

Related

I don't know what's the error in this code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
if(isset($_POST['submit'])) {
$img = $_FILES['image']['name'];
$target = 'img/'.basename($img);
$sql = move_uploaded_file($img, $target);
if ($sql) {
echo $img." uploaded";
}else {
echo $img." Failed";
}
}
if(!empty($_FILES['image'])) {
$path = "img/";
$path = $path . basename( $_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['image']['name'])." has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
I have checked your code it is perfectly fine. You need to take care of following few things.
1 - img directory should be have 777 rights.
2 - check your form tag properly.
Below is the sample for you.
<?php
if(!empty($_FILES['image'])) {
$img = $_FILES['image']['name'];
$target = 'img/'.basename($img);
//$sql = move_uploaded_file($img, $target); //replace $img with ($_FILES['image']['tmp_name']), you are not provide the tmp path of the image
$sql = move_uploaded_file(($_FILES['image']['tmp_name']), $target);
if ($sql) {
echo $img." uploaded";
}else {
echo $img." Failed";
}
}
?>
<form name="frm" id="id" action="" enctype="multipart/form-data" method="post">
<input type="file" name="image" id="image" >
<input type="submit" value="Upload" name="Upload">
</form>
Let me know if it helps?
First of all you should post what's the result you are getting and what did you expect, also you should've posted the html form code too.
The 2 if's seem related but are not connected ... maybe the second one should've been inside the first one ?
In the first if you are passing the wrong arguments to the move_uploaded_file method, the second one seems be good.
Ensure the "destination dir" is present, in the right location and has the correct permissions. Check apache's error_log for messages that might help.

Blank Screen After submitting form for Importing xls to mysql

This is code for importing its just showing a blank page after submitting a form with .xls file I dunno wats wrong in it my code please help me.
My database config file has no error in it , coz it is working fine with xls import from my sql.
Iam using linux server
HTML:
<form action="importData.php" method="post" enctype="multipart/form-data" id="importFrm1">
<input type="file" name="file" style="margin-top: 30px;px;" /><br>
<input type="submit" class="btn btn-primary" id="importSubmit" name="importSubmit" value="IMPORT" style="margin-top: 0px;">
</form>
This is my php code:importData.php
<?php session_start();
if(!isset($_SESSION['username'])) {
header("Location:sessionerror.php");
exit;
}
include "connection2.php";
//load the database configuration file
if(isset($_POST['importSubmit'])){
// Validate whether uploaded file is a csv file
$csvMimes = array('application/vnd.ms-excel','text/csv');
if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
if(is_uploaded_file($_FILES['file']['tmp_name'])){
//open uploaded csv file with read only mode
$csvFile = fopen($_FILES['file']['tmp_name'], 'r');
//skip first line
fgetcsv($csvFile);
// Parse data from csv file line by line
while (($line = fgetcsv($csvFile,1000, "\t")) !== FALSE){
$ID=$line[0];
$projectName=$line[1];
$projectLocation=$line[2];
$builderName=$line[3];
$builderGrade=$line[4];
$wheatherOCReceived=$line[5];
$startingPriceRs=$line[6];
$size_SBA=$line[7];
$configuration=$line[8];
$discount=$line[9];
$segment=$line[10];
$amenities=$line[11];
$filenme=$line[12];
$DateModified=$line[13];
//check whether member already exists in database with same email
$prevQuery = "SELECT id FROM info WHERE id = '".$line[0]."'";
$prevResult = $conn->query($prevQuery);
if($prevResult->num_rows > 0){
//update member data
$conn->query("UPDATE `featured_projects`.`info`
SET `projectName`='$projectName',`projectLocation`='$projectLocation',`builderName`='$builderName',`builderGrade`='$builderGrade',`wheatherOCReceived`='$wheatherOCReceived',`startingPriceRs`='$startingPriceRs',`size_SBA`='$size_SBA',`configuration`='$configuration',`discount`='$discount',`segment`='$segment',`amenities`='$amenities',`featuredImage`='$target_file',`date`='$DateModified'
WHERE `id` = '".$ID."'") or die("Unable to update: " . $conn->connect_error);
}else{
//insert member data into database
$conn->query("INSERT INTO `featured_projects`.`info` (`id`, `projectName`, `projectLocation`, `builderName`, `builderGrade`, `wheatherOCReceived`, `startingPriceRs`, `size_SBA`, `configuration`, `discount`, `segment`, `amenities`, `featuredImage`, `date`)
VALUES ('$ID', '$projectName', '$projectLocation', '$builderName', '$builderGrade', '$wheatherOCReceived', '$startingPriceRs', '$size_SBA', '$configuration', '$discount', '$segment', '$amenities', '$filenme', '$DateModified')" or die("Unable to Insert: " . $conn->connect_error);
}
}
//close opened csv file
fclose($csvFile);
$qstring = '?status=succ';
}else{
$qstring = '?status=err';
}
}else{
$qstring = '?status=invalid_file';
}
}
//redirect to the listing page
header("Location: admin-ready-home-in-bangalore2.php".$qstring);?>

how to upload an excel sheet and compare it with data in database?

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";
}
?>

how to upload a csv file and update the mysql db? [closed]

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);
}

How to get full filepath when uploading files in PHP?

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.

Categories