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