Cant Find File Error PHP - php

I am an extreme noob at this so please bear with me.
I have this small project where I am trying to upload a csv file and insert it into MySQL.
I have read all the similar posts here and tried out the things that I understood but I am still getting errors :D
<?php
$databasehost = "localhost";
$databasename = "hutchreport";
$databasetable = "intervalreport";
$databaseusername ="root";
$databasepassword = "";
if(isset($_POST['SUBMIT']))
{
$fname = $_FILES['csv_file']['name'];
$chk_ext = explode(".",$fname);
if(strtolower($chk_ext[1]) == "csv")
{
$filename = $_FILES['csv_file']['tmp_name'];
$con = #mysql_connect($databasehost,$databaseusername,
$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
$sql = "LOAD DATA LOCAL INFILE '$fname'
INTO TABLE intervalreport
FIELDS TERMINATED BY ','
LINES TERMINATED BY ',,,\\r\\n'
IGNORE 1 LINES (intervstartdate, intervstarttime, intervenddate,
intervendtime, loginname, loginnumber,
callsoffered, callsanswered, abandonedcalls,
waittime, staffedtime, auxtime, meeting,
coaching, logintime, inboundtalktime,
avginboundtalktime, inboundacwtime,
avginboundacwtime, inboundhandlingtime,
avginboundhandlingtime, heldcalls,
inboundholdtime, avginboundholdtime,
notreadytime, avgnotreadytime)";
mysql_query($sql) or die(mysql_error());
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}
?>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' enctype="multipart/form-data" method='post'>
<input type='file' name='csv_file' size='20'>
<input type='submit' name='SUBMIT' value='SUBMIT'>
</form>
</body>
</html>
I am getting the "Can't find file 'Book1.csv'" with this code. Please help!
EDIT: Finally got it to work. Here's the working code:
<html>
<head>
<title>
test
</title>
</head>
<body>
<?php
$databasehost = "localhost";
$databasename = "hutchreport";
$databasetable = "intervalreport";
$databaseusername="root";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "\n";
//$csvfile = "csv/Book1.csv";
if(isset($_POST['SUBMIT']))
{
$csvfile = $_FILES['csv_file']['tmp_name'];
move_uploaded_file($csvfile, $csvfile);
if(!file_exists($csvfile)) {
die("File not found. Make sure you specified the correct path.");
}
try {
$pdo = new PDO("mysql:host=$databasehost;dbname=$databasename",
$databaseusername, $databasepassword,
array(
PDO::MYSQL_ATTR_LOCAL_INFILE => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
die("database connection failed: ".$e->getMessage());
}
$affectedRows = $pdo->exec("
LOAD DATA LOCAL INFILE ".$pdo->quote($csvfile)." INTO TABLE `$databasetable`
FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)."
LINES TERMINATED BY ".$pdo->quote($lineseparator)."IGNORE 1 LINES (intervstartdate, intervstarttime, intervenddate, intervendtime, loginname, loginnumber, callsoffered, callsanswered, abandonedcalls, waittime, staffedtime, auxtime, meeting, coaching, logintime, inboundtalktime, avginboundtalktime, inboundacwtime, avginboundacwtime, inboundhandlingtime, avginboundhandlingtime, heldcalls, inboundholdtime, avginboundholdtime, notreadytime, avgnotreadytime)");
echo "Loaded a total of $affectedRows records from this csv file.\n";
} else { echo "invalid file";}
?>
<form action="" enctype="multipart/form-data" method='post'>
<input type='file' name='csv_file' size='20'>
<input type='submit' name='SUBMIT' value='SUBMIT'>
</form>
</body>
</html>

it would be so much better if have posted an image related to your error!And as php it self has expired the mysql functions it's better to use either PDO or mysqli!
i have corrected some part of the codes! please check and let me know if it has helped or not.
<?php
$databasehost = "localhost";
$databasename = "hutchreport";
$databasetable = "intervalreport";
$databaseusername ="root";
$databasepassword = "";
if(isset($_POST['SUBMIT']))
{
$fname = $_FILES['csv_file']['name'];
$chk_ext = explode(".",$fname);
if(strtolower($chk_ext[1]) == "csv")
{
$filename = $_FILES['csv_file']['tmp_name'];
$con = new mysqli($databasehost,$databaseusername,$databasepassword, databasename);
move_uploaded_file($filename, $filename);
$sql = "LOAD DATA LOCAL INFILE {$filename}
INTO TABLE intervalreport
FIELDS TERMINATED BY ','
LINES TERMINATED BY ',,,\\r\\n'
IGNORE 1 LINES (intervstartdate, intervstarttime, intervenddate,
intervendtime, loginname, loginnumber,
callsoffered, callsanswered, abandonedcalls,
waittime, staffedtime, auxtime, meeting,
coaching, logintime, inboundtalktime,
avginboundtalktime, inboundacwtime,
avginboundacwtime, inboundhandlingtime,
avginboundhandlingtime, heldcalls,
inboundholdtime, avginboundholdtime,
notreadytime, avgnotreadytime)";
$con->query($sql);
fclose($handle);
unlink($filename);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}
?>
<form action="" enctype="multipart/form-data" method='post'>
<input type='file' name='csv_file' size='20'>
<input type='submit' name='SUBMIT' value='SUBMIT'>
</form>
</body>
</html>
the thing i have done is i have uploaded file and save it to the parent directory! and then read the file and when the import thing has finished i have deleted the file!
hope it works

Related

I want to transfer data from a CSV file (which is on local computer) to Mysql table. Code gives error

my code is
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "onlinepaydb";
$studentTable = "studentregtable";
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
$uploadedFile = $_FILES["myfile"]["name"];
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_LOCAL_INFILE => true,));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "LOAD DATA LOCAL INFILE " . $uploadedFile . " INTO TABLE " . $studentTable . " FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES";
$conn->exec($sql);
echo "table studentTable updated successfully";
}
catch (PDOException $e)
{
echo $sql . $e->getMessage();
}
}
?>
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<meta name="viewport" content="width = device-width, initial-scale = 1">
</head>
<body>
<form method = "post" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" enctype = "multipart/form-data">
<label for = "selectfile">Select File:</label>
<input type = "file" name = "myfile" /><br>
<input type = "submit" name = "save" value = "Save" class = "save" />
</form>
</body>
</html>
error is:
LOAD DATA LOCAL INFILE student.csv INTO TABLE studentregtable FIELDS TERMINATED BY ',' LINES >>TERMINATED BY ' ' IGNORE 1 LINESSQLSTATE[42000]: Syntax error or access violation: 1064 You have an error >>in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax >>to use near 'student.csv INTO TABLE studentregtable FIELDS TERMINATED BY ',' ...' at line 1
I have the above code. The csv file is on local computer. database table is on the server. I expect it to transfer data from the CSV table to mysql table.
The syntax of CSV import by LOAD DATA is (if csv is named SOURCE.CSV and table name is TABLE_NAME and you want to ignore the 1st line which are the column names):
LOAD DATA LOCAL INFILE 'SOURCE.CSV' INTO TABLE TABLE_NAME FIELDS TERMINATED BY ','LINES TERMINATED BY '\n' IGNORE 1 LINES";
You may refer to the official documentation here:
https://dev.mysql.com/doc/refman/8.0/en/load-data.html
(1) So, please quote the filename (by single quotation marks)
(2) Please note that the uploaded file will be saved as $_FILES["myfile"]["tmp_name"] temporarily, in order for LOAD DATA to access the uploaded file, please move the uploaded file to your path (say of the same path of the PHP script) like this:
move_uploaded_file($_FILES["myfile"]["tmp_name"], "./". $uploadedFile);
(3) the path concerned must be writable for step 2 above to succeed.
Hence, assuming that you are going to upload the file to the same directory of the script, make sure that the directory is writable, then use the following code:
<?php
$servername = "localhost";
$username = "dbuser";
$password = "xxxxxxxxx";
$dbname = "onlinepaydb";
$studentTable = "studentregtable";
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
$uploadedFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"], "./". $uploadedFile);
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_LOCAL_INFILE => true,));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "LOAD DATA LOCAL INFILE '" . $uploadedFile . "' INTO TABLE " . $studentTable . " FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES";
$conn->exec($sql);
echo "table studentTable updated successfully";
}
catch (PDOException $e)
{
echo $sql . $e->getMessage();
}
}
?>
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<meta name="viewport" content="width = device-width, initial-scale = 1">
</head>
<body>
<form method = "post" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" enctype = "multipart/form-data">
<label for = "selectfile">Select File:</label>
<input type = "file" name = "myfile" /><br>
<input type = "submit" name = "save" value = "Save" class = "save" />
</form>
</body>
</html>

Import CSV file in MySql using PHP code

I've to import a CSV file in a table of a MySql database using PHP code. The CSV file is the following:
"2016-09-02", "100.01", "4005.09", "5000", "1.09", "120.09", "100.5", "200.77"
"2016-09-03", "150.01", "4205.09", "5600", "1.10", "150.09", "300.5", "300.77"
File permissions are 755.
Table fields are 9 (id field included): the firts is a datetime field and other are float fields.
The code I use is the following and it will run on the server site:
$csvFile = "../scripts/tabella.csv";
$db = #mysql_connect('**.***.**.***', 'Sql******', '*******');
#mysql_select_db('Sql******_*');
$query = 'LOAD DATA LOCAL INFILE \' '. $csvFile .' \' INTO TABLE mytable FIELDS TERMINATED BY \',\' ENCLOSED BY \'"\' LINES TERMINATED BY \'\n\' ';
if(!mysql_query($query)){
die(mysql_error());
}
mysql_close($db);
First error is returned from mysql_error: 'file not found'. The CSV file is in 'www.mysite.it/mysite/scripts/tabella.CSV'. Its permissions are 755. I tried to use realpath($csvFile) function but the error is always the same.
I tried to run the same query in localhost and there isn't this error but only a record is inserted into the table and its fild values are NULL.
Can you help me, please?
Thanks!
Use mysql_error to get the error
if(!mysql_query($query)){
die(mysql_error());
}
Try below code..
$csvFile = "../scripts/tabella.csv";
//The Connection
$mysqli = new mysqli($host,$username,$password,$database);
//Check for successful connection
if ($mysqli->connect_errno) echo "Error - Failed to connect to MySQL: " . $mysqli->connect_error; die;
$query = 'LOAD DATA LOCAL INFILE \' '. $csvFile .' \' INTO TABLE mytable FIELDS TERMINATED BY \',\' ENCLOSED BY \'"\' LINES TERMINATED BY \'\n\' ';
//Do your query
$result = mysqli_query($mysqli,$query);
//Close the connection
mysqli_close($mysqli);
Try This coding It's work
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["submit"]))
{
if($_FILES['file']['name'])
{
$filename = explode(".", $_FILES['file']['name']);
if($filename[1] == 'csv')
{
$handle = fopen($_FILES['file']['tmp_name'], "r");
while($data = fgetcsv($handle))
{
$item1 = mysqli_real_escape_string($connect, $data[0]);
$item2 = mysqli_real_escape_string($connect, $data[1]);
$query = "INSERT into excel(excel_name, excel_phone) values('$item1','$item2')";
mysqli_query($connect, $query);
}
fclose($handle);
echo "<script>alert('Import done');</script>";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<form method="post" enctype="multipart/form-data">
<div align="center">
<label>Select CSV File:</label>
<input type="file" name="file" />
<br />
<input type="submit" name="submit" value="Import" class="btn btn-info" />
</div>
</form>
</body>
</html>
try this simple way to import your CSV data to Mysql database.The file is a HTML element name to browse your file path.
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name= $filesop[0];
$sql = mysql_query("INSERT INTO tab(name) VALUES ('$name')");
$c = $c + 1;
}
if($sql){
echo "You database has imported successfully. You have inserted ". $c ." recoreds";
}else{
echo "Sorry! There is some problem.";
}
}

Import TXT file Into MySQL table every 5 seconds

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'root';
$database = 'test';
$table = 'test';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
if(isset($_POST['submit']))
{
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) == "txt")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql = "INSERT into graph(note,per,cpu,perc) values('$data[0]','$data[1]','$data[2]','$data[3]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}
?>
<h1>Import txt file</h1>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype="multipart/form-data">
Import File : <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>
This is my code for import txt file into MySQL table.
But I want to this code automatically import txt file to mysql every 5 seconds.
It mean I will setup url of txt file and every 5 seconds , it will import to mysql.
Please help me and sorry my English . thanks all
If you need to import a file every 5 seconds from a list of files that is growing, then you should set up a cron job for that. Or if you want to import, say just 50(small) files or so, then you can put your code inside a recursive function with a sleep time of 5 seconds and execute it via shell. Also do use MySQLi or PDO_MySQL extension as the MySQL(Original) extension is deprecated.

execute another php file within one php within loop

I have a php code that has if statements(to export as pdf, to export as excel and the last one to upload excel).
The first two if's to upload pdf and excel are working fine, when I click on the button to run the the third if statement, it shows me blank page, even though the code for it is working fine when I run it separately.
My php code is below:
<?php
define('FPDF_FONTPATH','/Applications/XAMPP/xamppfiles/lib/php');
if (isset($_POST['pdf'])) {
//code//
}
}
if (isset($_POST['excel'])) {
//code//
}
if (isset($_POST['upload'])) {
exec( 'imp.php');
}
?>
The imp.php file which I am trying to run is:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';
$database = 'mydatabase';
$table = 'demo';
if (!#mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
if(isset($_POST['submit']))
{
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) == "csv")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql = "INSERT into demo(orders,quantity,country,dates,comment) values('$data[0]','$data[1]','$data[2]', '$data[3]','$data[4]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}
?>
<h1>Import CSV file</h1>
<form action='<?php echo $_SERVER["PHP_SELF"];?>' method='post' enctype="multipart/form-data">
Import File : <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form
exec function executes file on server. You won't see anything unless you explicitly get result of exec to a variable and output it.
But as I see - you just want to include some php file into another - for this are include and require are supposed:
include '/path/to/file.php';
This will be enough.

Button upload issue

I have been struggling for some time with getting this single button upload to work, i have tried several methods to submit the upload and this one i have seems to work up to the point of the php but then something in the php seems to not like the submit, without the js this works as a regular select file and upload, but soon as i add the js (which appears to work) the php then doesnt work.
Im totally confused why this is happening!
Any advice appreciated thanks!
The upload form
<form name="form" method="POST" enctype="multipart/form-data" action="updateProfilePic_script.php">
<div class="update_header_pic">
<input type = 'button' value = 'Choose image'
onclick ="javascript:document.getElementById('Photo').click();">
<input id='Photo' type='file' style='visibility: hidden;' name='Photo' onchange='submit();'/>
</div>
</form>
The php
<?
session_start();
$user = $_SESSION['username'];
$hostname = "localhost";
$db_user = "xxxusername";
$db_password = "xxxpassword";
$database = "xxxdatabase";
$db_table = "user_profile_pic"; // image table
# THIS CODE IS USED TO CONNECT TO THE MYSQL DATABASE
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db);
$uploadDir = 'usermedia/users/images/profileimages/'. $user .'/';//Image Upload Folder
if (!is_dir($uploadDir) && !mkdir($uploadDir)){
die("Error creating folder $uploadDir");
}
if(isset($_POST['submit'])) {
$date = date("Y-m-d H:i:s");
$unique = substr(number_format(time() * rand(),0,'',''),0,10);
$fileName = $unique .'-'.$_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image , username , datetime , filesize , filetype ) VALUES ('$filePath' , '$user' , '$date' , '$fileSize' , '$fileType' )";
mysql_query($query) or die('Error, query failed');
header('Location: edit_myProfile.php');
}
?>
In your HTML form there is no [input type=submit] then why in your PHP code you did:
if(isset($_POST['submit'])) {
//...
//..
}
You can simply change it to:
if(isset($_FILES['Photo'])) {
//the your uploading procedure
}

Categories