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.";
}
}
Related
<?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.
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.
I am trying to upload a image to MySQL databases using php5 script. And I am receiving an notice error.
Error, query failed
UploadImage.php
<?php
session_start();
?>
<HTML>
<HEAD>
<TITLE> Image Upload</TITLE>
</HEAD>
<BODY>
<FORM NAME="f1" METHOD="POST" ACTION="uploadImage2.php" ENCTYPE="multipart/form-data">
<table>
<tr><td> Image Upload Page </td></tr>
<tr><td> <input type="file" name="imgfile"/></td></tr>
<tr><td> <input type="submit" name="submit" value="Save"/> </td></tr>
</table>
</FORM>
</BODY>
</HTML>
UploadImage2.php
<?php
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
if(isset($_REQUEST['submit']) && $_FILES['imgfile']['size'] > 0)
{
$fileName = mysql_real_escape_string($_FILES['imgfile']['name']); // image file name
$tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
$fileSize = mysql_real_escape_string($_FILES['imgfile']['size']); // size of the uploaded file
$fileType = mysql_real_escape_string($_FILES['imgfile']['type']); //
$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
$imgContent = fread($fp, filesize($tmpName)); // read the temp file
$imgContent = mysql_real_escape_string($imgContent);
fclose($fp); // close the file handle
$query = "INSERT INTO img_tbl (img_name, img_type, img_size, img_data )
VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent')";
mysql_query($query) or die('Error, query failed'.mysql_errno($dbconn) . ": " . mysql_error($dbconn) . "\n");
$imgid = mysql_insert_id(); // autoincrement id of the uploaded entry
//mysql_close($dbconn);
echo "<br>Image successfully uploaded to database<br>";
echo "View Image";
}else die("You have not selected any image");
?>
I have upload an image file but still have error on it.
But now I have counter another error for view Image.
<?php
// get the file with the id from database
include "dbconfig.php";
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die("Error Occurred-".mysql_error());
mysql_select_db($dbname, $dbconn) or die("Unable to select database");
if(isset($_REQUEST['id']))
{
$id = $_REQUEST ['id'];
$query = "SELECT img_name, img_type, img_size, img_data FROM img_tbl WHERE id = ‘$id’";
$result = mysql_query($query) or die(mysql_error());
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
print $content;
mysql_close($dbconn);
}
?>
The error code:
Notice: Undefined variable: id� in C:\xampp\htdocs\sandbox\Testing\uploadImage2_viewimage.php on line 12
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '�' at line 1
Please advise...
Remove the ' ' from table fields in query .use this query :
$query = "INSERT INTO img_tbl (img_name, img_type, img_size, img_data )
VALUES ('$fileName', '$fileType', '$fileSize', '$imgContent')";
also please start to use PDO or mysqli as your query is open for sql injection
This should work:
$query = "
INSERT INTO `img_tbl`
(`img_name`, `img_type`, `img_size`, `img_data` )
VALUES
('".$fileName."', '".$fileType."', '".$fileSize."', '".$imgContent."')
";
Seems that some special characters in $imgContent is breaking the query string
Please use mysql_real_escape_string to format your data before sending to the database
mysql_real_escape_string
$fileName = mysql_real_escape_string($_FILES['imgfile']['name']); // image file name
$tmpName = $_FILES['imgfile']['tmp_name']; // name of the temporary stored file name
$fileSize = mysql_real_escape_string($_FILES['imgfile']['size']); // size of the uploaded file
$fileType = mysql_real_escape_string($_FILES['imgfile']['type']); //
$fp = fopen($tmpName, 'r'); // open a file handle of the temporary file
$imgContent = fread($fp, filesize($tmpName)); // read the temp file
$imgContent = mysql_real_escape_string($imgContent);
fclose($fp); // close the file handle
UPDATE
If the first solution didn't fix the problem , please check are there any NULL values , you have some database columns which set to NOT NULL . so you cannot insert NULL values to them .
Hope this helps :)
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
I am trying to upload the contact data of csv to mysql database phbook using php,
but when i check through phpmyadmin or print the data of the database.. i dont see anything, or say the table is empty,
The code i used is as below;
<?php
/* conenction to DB */
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("phbook", $con);
/* connection ends*/
if ( isset( $_FILES['userfile'] ) )
{
$csv_file = $_FILES['userfile']['tmp_name'];
if ( ! is_file( $csv_file ) )
exit('File not found.');
$sql = '';
if (($handle = fopen( $csv_file, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql .= "INSERT INTO `contact` SET
`fname` = '$data[0]',
`lname` = '$data[1]',
`phone` = '$data[2]',
`mob` = '$data[3]',
`email` = '$data[4]';
";
}
fclose($handle);
}
// Insert into database
//exit( $sql );
exit( "Complete!" );
}
mysql_close($con);
?>
<!DOCTYPE html>
<html>
<head>
<title>CSV to MySQL Via PHP</title>
</head>
<body>
<form enctype="multipart/form-data" method="POST">
<input name="userfile" type="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
I have used the code the Import an excel (.csv) into MySQL using PHP code and an HTML form
You need to call mysql_query to execute to query. Right now you only formulate the query as a string ($sql) and do nothing further. Just pass this string as a parameter, like:
$result = mysql_query($sql);
You may also want to handle any errors that occur. For instance (from PHP manual):
if (!$result) {
die('Invalid query: ' . mysql_error());
}
For details, see PHP manual on mysql_query.
For the help of others like me who are seeking for a solution, read this and follow,
I created a database named csv, and table named test, where the 4 fields are id (auto increment and primary) , first_name, last_name, email. I have created a csv file and named it upload.csv(doesnt matter what you name it) where there are hundreds of data of individuals in 3 columns like First Name, Last Name and Email Address example:
willie walker willie#example.com
david cotter david#sometest.com
John Painer john#domain.com
....... .......... ......................
....... .......... ......................
Now, create a new php file import_csv_file.php(doesnt matter what you name it) and paste the codes below, save it and run under your webserver..Upload the csv file that we had created and see.. IT WORKS
<?php
$con = mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db('csv', $con);
if(isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false)
{
$f = $fileop[0];
$l = $fileop[1];
$e = $fileop[2];
$sql= mysql_query("INSERT INTO test (first_name,last_name,email) VALUES ('$f','$l','$e')");
}
if($sql)
{
echo "data uploaded successfully";
}
}
?>
<body>
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="file" />
<br />
<input type="submit" value="Submit" name="submit"/>
</form>
</body>
</html>