csv to mysql using php no data inserted - php

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>

Related

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

Broken Image when uploading it to MySQL Database

I am trying to store images into a path and then upload them into my database. The DB is called "store" and the table I'm using is called "images" containing 3 fields: id, name (varchar), image (longblob). The form is the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload an Image</title>
</head>
<body>
<form action="upload_file.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="262144000" />
<p>File:</p>
<input type="file" name="image" accept="image/jpeg" accept="image/jpg" accept="image/png" accept="image/gif">
<input type="submit" value="Upload" name="submit" />
</form>
</body>
</html>
The upload_file.php is:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
//file properties
$file = $_FILES['image']['tmp_name'];
if(!isset($file)){
echo "<p>Please select an image.</p>";
} else {
//$image = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$image = base64_encode(file_get_contents($_FILES['image']['tmp_name']));
$image_name = mysql_real_escape_string($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "<p>Sorry, this is not an image.</p>";
} else {
echo "<p>File is an image. Processing...</p>";
if(!$insert = mysql_query("INSERT INTO images VALUES('','$image_name','$image')")){
echo "<p>Problem uploading image:".mysql_error()."</p>";
} else {
$lastid = mysql_insert_id();
echo "<p>Success!</p>";
echo "<img src=get.php?id=$lastid>";
}
}
}
error_reporting(-1);
?>
And get.php is:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
$id = $_REQUEST['id'];
$image = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_array($image);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
?>
The images are uploaded, but are not shown. Instead, I get a broken image icon, and I don't understand why. Can someone help me??
Try to solve this problem step by step
This process can be identified as three parts and split up quickly. The HTML form, the PHP upload and saving to database process, and the loading from database process.
Try echoing the image data before inserting it into the database to see if the data is actually correct.
Update the database and see if the data is inserted there.
Load the image data from the database and echo it to see if it loads it correctly.
Try the full script.
This is just an example checklist. But you can change this and add more steps to it.
Also, please consider updating to MySQLi. You are using deprecated functions which could lead to security issues. Many information sources regarding this subject can be found on the web.
Correct the get.php code with this code
<?php
//Connect to database
$conn = mysql_connect("localhost", "tester", "");
if (!$conn) {
die("Could not connect to MySQL");
}
if (!mysql_select_db("tester")) {
die("Could not open database:" . mysql_error());
}
$id = $_REQUEST['id'];
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
You have to change the database name and user whit your own
These are the parts that i have changed:
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
echo base64_decode($image);

Cannot upload image into mysql database use php

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 :)

Cant Find File Error 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

php array file is empty when uploading file

when i upload file it show array file empty, however upload is on in my php.ini.
please see my code blow and let me know where is the error.
i have looked all around the web for solution but did not found, im using PHP Version 5.3.25 on centos 5.4 kernel version 2.6.18-164.el5.
thanks and regards
hadi
html page.
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
<p>
See all files
</p>
</body>
</html>
add_file.php
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('127.0.0.1', 'user', 'pwd', 'myTable');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(
file_get_contents($_FILES['uploaded_file']['tmp_name'])
);
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
} else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
} else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
} else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>

Categories