i got a PHP script to import a file into my mysql database.
but when i try to use it i get this error:
File not found. Make sure you specified the correct path
but i did not even select a file this is my script:
<?php
include ('db_connect.php');
//connect to the database
//
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO test (nummer, branche) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
)
");
}
} while ($data = fgetcsv($handle,10000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
any1 who can hlp me with this problem?
Re comment about do/while loop: no, I mean like this
$handle = fopen($file,"r");
if ($handle !== FALSE) {
while (!feof($handle)) {
$data = fgetcsv($handle,10000,",","'");
if ($data[0]) {
mysql_query("INSERT INTO test (nummer, branche) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."'
)
");
}
}
fclose($handle);
}
Related
I am planning to make an image galary using PHP with MySQL as a database.
I already make a multiple upload images using PHP but I got a problem. When I uploaded 8 images in database only show 1 row data. But in folder there are 8 images that I have upload.
Here is my code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>
<?php
include_once 'koneksi.php';
if(isset($_POST['btn_upload']))
{
for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
{
$filetmp = $_FILES["file_img"]["tmp_name"][$i];
$filename = $_FILES["file_img"]["name"][$i];
$filetype = $_FILES["file_img"]["type"][$i];
$filepath = "uploads/".$filename;
move_uploaded_file($filetmp,$filepath);
$sql = "INSERT INTO files (file,path,type) VALUES ('$filename','$filepath','$filetype')";
if($connect->query($sql) === TRUE) {
header("Location: a.php");
} else {
header("Location: a.php");
}
}
$connect->close();}
?>
</body>
</html>
Can someone help me ? Thanks for ur feedback :)
Move the header location redirect outside the for loop.
Also Refer Upload multiple images and store their path in database.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>
<?php
include_once 'koneksi.php';
if(isset($_POST['btn_upload']))
{
for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
{
$filetmp = $_FILES["file_img"]["tmp_name"][$i];
$filename = $_FILES["file_img"]["name"][$i];
$filetype = $_FILES["file_img"]["type"][$i];
$filepath = "uploads/".$filename;
move_uploaded_file($filetmp,$filepath);
$sql = "INSERT INTO files (`file`,`path`,`type`) VALUES ('$filename','$filepath','$filetype')";
$connect->query($sql);
}
if($connect->query($sql) === TRUE) {
header("Location: a.php");
exit; // always add exit after header Location:
} else {
header("Location: a.php");
exit; // always add exit after header Location:
}
$connect->close();}
?>
</body>
</html>
After some code beautification of your snippet answer became obvious - you only get one new row in database, because in your for loop you redirect user to a.php right after inserting this row.
In other words your for loop will always perform one and only one step.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>
<?php
include_once 'koneksi.php';
if (isset($_POST['btn_upload'])) {
for ($i = 0; $i < count($_FILES['file_img']['name']); $i++) {
$filetmp = $_FILES["file_img"]["tmp_name"][$i];
$filename = $_FILES["file_img"]["name"][$i];
$filetype = $_FILES["file_img"]["type"][$i];
$filepath = "uploads/".$filename;
move_uploaded_file($filetmp, $filepath);
$sql = "INSERT INTO files (file, path, type) VALUES ('$filename','$filepath','$filetype')";
// #NOTICE: Read about SQL Injection and why above SQL is bad.
// #SOLUTION: Place 1
if ($connect->query($sql) === true) {
header("Location: a.php");
exit; // #NOTICE: Always add `exit` after "header Location:"
} else {
header("Location: a.php");
exit; // #NOTICE: Always add `exit` after "header Location:"
}
}
$connect->close();
// #SOLUTION: Place 2
}
?>
</body>
</html>
Can you see it now?
Checkout link below! File [1] is your file after performing some cleaning. It's also contains two comments marked as #SOLUTION. Place 1 is the code you should move to Place 2. After moving you should also change if condition to check if all files were uploaded correctly. File [2] on the other hand is edited by me with (probably) proper solution for your problem.
I hope I helped!
https://github.com/broiniac/stackoverflow/blob/master/44346949/
EDIT: #AdhershMNair:
I think that because of line if($connect->query($sql) === TRUE) { in your solution, data for last uploaded file will be inserted into database twice (once for last iteration in for loop and once for if statement).
i want to add an image's path with android to mysql database using a php file. i added the path with a php file to the database but i failed to connect the android app to the php file si i can put the path of the image from android to mysql database can anyone tell me the rignt procedure for doing it ?
this is my php file :
<?php
define('hostname','localhost');
define('user', 'root');
define('password', '');
define('databasename', 'image');
$connect=mysqli_connect(hostname,user,password,databasename);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img" />
<input type="submit" name="btn_upload" value="Upload">
</form>
<?php
if(isset($_POST['btn_upload']))
{
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filepath = "photo/".$filename;
move_uploaded_file($filetmp,$filepath);
$sql = "INSERT INTO img (img_name,img_path,img_type) VALUES ('$filename','$filepath','$filetype')";
$result = mysqli_query($connect,$sql);
}
?>
</body>
</html>
I have a table in database with fields (Id,Name,Email,Employee Code,Joining Date,Address) and i have a csv file which containing same fields. I have to import csv file into database with same header. If header is different then it should not import into database and throw an error. I have to check while uploading csv into database, if any value(email or Employee code) is already in the database then it should ignore the field and throw an error.
Please help .
if(isset($_POST["Import"]))
{
$host="localhost"; // Host name.
$db_user="root";
$db_password="password";
$db='testcsv'; // Database name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
$fieldinfo=array();
echo $filename=$_FILES["file"]["tmp_name"];
$query="SELECT * FROM csv";
$output=mysql_query($conn,$query);
while ($fieldinfo=mysqli_fetch_field($output))
{
$columns=$fieldinfo;
}
echo $query;
echo "<br/>";
print_r($output);
echo "<br/>";
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
$header = fgetcsv($file);
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$record = array_combine($header, $emapData);
echo "<br>";
echo $record;
echo "<br>";
$sql = "INSERT into csv(Name,Email,EmployeeCode,JoiningDate,Address) values('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]')";
mysql_query($sql);
}
fclose($file);
echo "CSV File has been successfully Imported";
}
else
echo "Invalid File:Please Upload CSV File";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import CSV/Excel file</title>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<table border="1" width="40%" align="center">
<tr >
<td colspan="2" align="center"><strong>Import CSV/Excel file</strong></td>
</tr>
<tr>
<td align="center">CSV/Excel File:</td><td><input type="file" name="file" id="file"></td></tr>
<tr >
<td colspan="2" align="center"><input type="submit" name="Import" value="Import"></td>
</tr>
</table>
</form>
</body>
</html>
Here I am using this php code for insert multiple images in one field in database table but after insert a row is taking one extra row after each insert .......Help me to solve this issue..
Thank you Advance.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
/*if(isset($_REQUEST['submit']))
{
$pname=$_FILES['image']['name'];
$tmp_name=$_FILES['image']['tmp_name'];
move_uploaded_file($tmp_name."photo/".$pname);
$fileext = pathinfo($pname, "photo/");
$fileext = strtolower($fileext);
}*/
$uploads_dir = 'photo/';
//$images_name ="";
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = $_FILES["image"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$images_name =$images_name.$name.",";
}
}
$sql=mysql_query("INSERT INTO multiimg(image) values('".$images_name."')");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function addmore(num)
{
if(num==1)
{
document.getElementById('field2').style.display='block';
document.getElementById('ni1').style.display='block';
return false;
}
else if(num==2)
{
document.getElementById('field3').style.display='block';
return false;
}
}
</script>
</head>
<body>
<form enctype="multipart/form-data" name="" action="" method="post">
<div id="field1">Enter One Image :<input type="file" name="image[]" id="img1"/>addmore...</div>
<div id="field2" style="display:none;">Enter Two Image :<input type="file" name="image[]" id="img2"/>add more...</div>
<div id="field3" style="display:none;">Enter Three Image :<input type="file" name="image[]" id="img3"/>addmore...</div>
<div id="field4" style="display:none">Enter Forth Image :<input type="file" name="image[]" id="img4"/>addmore...</div>
<input type="submit" name="submit"/>
</form>
</body>
</html>
please check if the form is posted then do the insert ,else while loading the page a row will be inserted in table with empty data
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
if(isset($_POST['submit'])){
$uploads_dir = 'photo/';
//$images_name ="";
foreach ($_FILES["image"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["image"]["tmp_name"][$key];
$name = $_FILES["image"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
$images_name =$images_name.$name.",";
}
}
$sql=mysql_query("INSERT INTO multiimg(image) values('".$images_name."')");
}
?>
What i want to know is how can I get a list [specifically array] of all the files name in a directory when I select it through upload button, after which I would upload that array of files to the database. As one file as a single entry. So how do I do that?
No to forget that I just need files names and I have to upload these names only not the actual files.
are the files on the server? if you hopping to have a button you click on browser and open a folder on the end user this will not work. most browsers only allow single file selection
If you are using ftp, this function will return all of the filenames of a directory in an array.
function ftp_searchdir($conn_id, $dir) {
if(!#ftp_is_dir($conn_id, $dir)) {
die('No such directory on the ftp-server');
}
if(strrchr($dir, '/') != '/') {
$dir = $dir.'/';
}
$dirlist[0] = $dir;
$list = ftp_nlist($conn_id, $dir);
foreach($list as $path) {
$path = './'.$path;
if($path != $dir.'.' && $path != $dir.'..') {
if(ftp_is_dir($conn_id, $path)) {
$temp = ftp_searchdir($conn_id, ($path), 1);
$dirlist = array_merge($dirlist, $temp);
}
else {
$dirlist[] = $path;
}
}
}
ftp_chdir($conn_id, '/../');
return $dirlist;
}
<?
if (isset($_POST[submit])) {
$uploadArray= array();
$uploadArray[] = $_POST['uploadedfile'];
$uploadArray[] = $_POST['uploadedfile2'];
$uploadArray[] = $_POST['uploadedfile3'];
foreach($uploadArray as $file) {
$target_path = "upload/";
$target_path = $target_path . basename( $_FILES['$file']['name']);
if(move_uploaded_file($_FILES['$file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['$file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload-simple.php" method="POST">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload:
<input name="uploadedfile" type="file" />
</p>
<p>Choose a file to upload:
<input name="uploadedfile2" type="file" />
</p>
<p>Choose a file to upload:
<input name="uploadedfile3" type="file" />
<input name="submit" type="submit" id="submit" value="submit" />
</p>
</form>
</body>
</html>
This Might be Solve your Problems
If the files already exist on the server you can use glob
$files = glob('*.ext'); // or *.* for all files
foreach($files AS $file){
// $file is the name of the file
}