importing csv file to database using php - php

I have created the following php code to import .csv file into mysql database running on phpmyadmin. The code is as follows:
<?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>
Once I submit the .csv file, it shows the message"imported successfully" however when I check the database only the first row in the .csv file is imported to database. Other records are not.

Don use mysql_ change it to PDO or mysqli. That being said I've changed your code to explode each row and then assing the values to a list. It worked for me.
if(isset($_POST['submit']))
{
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$fname.' ';
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) == "csv")
{
foreach (file($fname) as $row)
{
list($data0, $data1, $data2, $data3, $data4) = explode(",", $row);
$sql = "INSERT into demo(orders,quantity,country,dates,comment) values('$data0','$data1','$data2', '$data3','$data4')";
mysql_query($sql) or die(mysql_error());
}
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}

Related

Not able to insert proper "voice file(mp3) " into database

Able to insert the data but the format which gets inserted is not working ...tried with image files, voice files etc.
Using blob data type able to insert the file data inside the MySQL database, but the format is not working.
<?php
$server = "localhost";
$user = "USERNAME";
$pass = "PASSWORD";
$db = "databasename";
$con = new mysqli($server, $user, $pass, $db);
if ($con->connect_error) {
die("connection error");
}
$inscrutable = "insert into tables(id, data,filepath) values(1,'voice.mp3','F:\\\')";
if ($con->query($inscrutable) == true) {
echo "Inserted successfully";
} else {
echo "error" .$con->error;
}
$con->close();
Required to login to the page with a voice recorder
connecting database
//file_name config.php
<?php
$host = ""; /* Host name */
$user = ""; /* User */
$password = ""; /* Password */
$dbname = ""; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<!doctype html>
<html>
<head>
<?php
include("config.php");
if(isset($_POST['upload'])){
$maxsize = 5242880; // 5MB
$name = $_FILES['file']['name'];
$target_dir = "videos/";
$target_file = $target_dir . $_FILES["file"]["name"];
// Select file type
$audioFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("MP3","WAV","FLAC","PCM","AIFF");
// Check extension
if( in_array($audioFileType,$extensions_arr) ){
// Check file size
if(($_FILES['file']['size'] >= $maxsize) || ($_FILES["file"]["size"] == 0)) {
echo "File too large. File must be less than 5MB.";
}else{
// Upload
if(move_uploaded_file($_FILES['file']['tmp_name'],$target_file)){
// Insert record
$query = "INSERT INTO tables(name,location) VALUES('".$name."','".$target_file."')";
mysqli_query($con,$query);
echo "Upload successfully.";
}
}
}else{
echo "Invalid file extension.";
}
}
?>
</head>
<body>
<form method="post" action="" enctype='multipart/form-data'> //must use enctype = "multipart/form-data"
<input type='file' name='file' />
<input type='submit' value='Upload' name='upload'>
</form>
</body>
</html>

How to improve bulk mysql insert with php to grab all directories and images from directory at once

I got a working image from directory to mysql inserting script.the problem is that i after every directory i need to change the name in script itself to insert next images from other directory. every file and every diretory with images is in a prent directory called "images". so my question how can i say insert everything in the mysql db from this directory and use the names of the directory as category names for images in it.
<?php
$server = 'xxxxx';
$dbuser = 'xxxxxx';
$dbpass = 'xxxxxx';
$dbname = 'xxxxxxx';
$connect = mysql_connect($server,$dbuser,$dbpass);
mysql_select_db($dbname,$connect);
$path = "images/thanks/";
$files = array_map('mysql_real_escape_string',array_filter(glob("{$path}*.*"),'is_file'));
if(empty($files)){
echo "There were no matching files to insert into the database.";
} else {
$insertValues = array();
foreach($files as $file)
{
$data = getimagesize($file);
$width = $data[0];
$height = $data[1];
$insertValues[] = "('Titel', 'thanks', '{$file}', '$width', '$height')";
}$query = "INSERT INTO `gbpics` (`gbpictitel`, `gbpiccat`, `gbpicurl`, `gbpicwidth`, `gbpicheight`) VALUES " . implode(', ', $insertValues);
if(!mysql_query($query)){
echo "There was a problem inserting the data.";
trigger_error("Query failed: $query<br />Error: " . mysql_error());
} else {
echo "The data was inserted successfully.";
}
}?>
try this :
<?php
$server = 'xxxxx';
$dbuser = 'xxxxxx';
$dbpass = 'xxxxxx';
$dbname = 'xxxxxxx';
$connect = mysql_connect($server, $dbuser, $dbpass);
mysql_select_db($dbname, $connect);
$dirs = array_filter(glob('images/*'), 'is_dir');
foreach ($dirs as $dir) {
$path = "images/" . $dir . "/";
$files = array_map('mysql_real_escape_string', array_filter(glob("{$path}*.*"), 'is_file'));
if (empty($files)) {
echo "There were no matching files to insert into the database.";
} else {
$insertValues = array();
foreach ($files as $file) {
$data = getimagesize($file);
$width = $data[0];
$height = $data[1];
$insertValues[] = "('Titel', {$dir}, '{$file}', '$width', '$height')";
}
$query = "INSERT INTO `gbpics` (`gbpictitel`, `gbpiccat`, `gbpicurl`, `gbpicwidth`, `gbpicheight`) VALUES " . implode(', ', $insertValues);
if (!mysql_query($query)) {
echo "There was a problem inserting the data.";
trigger_error("Query failed: $query<br />Error: " . mysql_error());
} else {
echo "The data was inserted successfully.";
}
}
}
?>
btw you have pretty deprecated code here...
dont use mysql_ use mysqli_

can't complete on fgetcsv in mysql

<?php
header('Content-Type: text/html; charset=utf-8');
$servername = "localhost";
$username = "root";
$password = "abc";
$dbname = "project";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "TRUNCATE TABLE datapack";
mysqli_query($conn,$sql);
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");
$head = fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql= "INSERT into datapack(id,nickname,time,msg) values('$data[0]','$data[1]','$data[2]','$data[3]')";
mysqli_query($conn,$sql);
echo "Error: ". $conn->error;
}
echo "Success!";
}
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>
After I run the file, i find some problems:
The file cannot completely import to mysql (for example, only 600 lines can imports when there is 1000 lines in csv), and everytime i run it, the number of lines importing to mysql is different.
It cannot echo success.
When echo the error, some lines it tells me incorrect string values. I thought it was uft-8 problems, but after I just get id and time only, the situation is also the same in point 1
Most importantly, you are not escaping your data. There could be anything in that CSV, breaking that query. Also, you're limiting the line length (so if there are long lines they will not get inserted) and aren't checking for the proper number of columns in the CSV file. Try changing these things:
<?php
$servername = "localhost";
$username = "root";
$password = "abc";
$dbname = "project";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit']))
{
$fname = $_FILES['sel_file']['name'];
echo "Uploaded file name: $fname";
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) === "csv") {
$sql = "TRUNCATE TABLE datapack";
$conn->query($sql);
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
$head = fgetcsv($handle);
$sql= "INSERT INTO datapack (id, nickname, time, msg) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
while (($data = fgetcsv($handle)) !== FALSE) {
if (count($data) < 4) {
echo "Error, not 4 columns";
continue;
}
$stmt->bind_param("isss", $data[0], $data[1], $data[2], $data[3]);
if (!$stmt->execute()) {
echo "Error: ". $stmt->error;
} else {
echo "Success!";
}
}
else {
echo "Invalid File";
}
}
?>
<h1>Import CSV file</h1>
<form action="" method="post" enctype="multipart/form-data">
Import File : <input type='file' name='sel_file' size='20'>
<input type='submit' name='submit' value='submit'>
</form>
Note the default HTML behaviour is to post to itself; by needlessly adding $_SERVER["PHP_SELF"] you open yourself up to script injection attacks.
executing 1000 query may be too expensive in small servers.
instead you may do bulk insertion .
$sql= "INSERT into datapack(id,nickname,time,msg) values";
$sqlArray = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sqlArray[] = "('$data[0]','$data[1]','$data[2]','$data[3]')";
}
$sql .= " " . implode(", ", $sqlArray);
mysqli_query($conn,$sql);
echo "Error: ". $conn->error;
However , this would be a great chance to begin using begin_transaction for such a case.
mysqli_begin_transaction
Begins a transaction. Requires MySQL 5.6 and above, and the InnoDB
engine (it is enabled by default). For additional details about how
MySQL transactions work, see ยป
http://dev.mysql.com/doc/mysql/en/commit.html.

Try uploading csv file to mysql using php and mysql

Good day everyone, I am quite new to php and I really need some help. I am trying to upload a csv file to mysql database using php and html form, but it is giving me the following errors:
Notice: Undefined index: temp_name in C:\xampp\htdocs\import csv\importcsv.php on line 23
Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\import csv\importcsv.php on line 24
Warning: fgetcsv() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\import csv\importcsv.php on line 26
Warning: fclose() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\import csv\importcsv.php on line 30 successfully imported
here is my code
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';
$db = 'mydb';
$table = 'user';
$conn = mysqli_connect($db_host, $db_user, $db_pwd) or die("Cant connect to database");
if(!mysqli_select_db($conn,$db))
die("Cant select to 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']['temp_name'];
$handle = fopen($filename, "r");
while(($data = fgetcsv($handle, 1000, ",")) != FALSE){
$sql = "INSERT into user(name,email,phone) values('$data[0]', '$data[1]', '$data[2]')";
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>
Can anyone please help me out
I have updated some lines in your code.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';
$db = 'mydb';
$table = 'user';
$conn = mysqli_connect($db_host, $db_user, $db_pwd, $db) or die("Cant connect to database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
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 user(name,email,phone) values('".$data[0]."', '".$data[1]."', '".$data[2]."')";
mysqli_query($conn, $sql) or die(mysqli_error($conn));
}
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>

MySQL returned an empty result set

i dont understand why mysql table return empty result set, the code seems okay.
the response from mysql: MySQL returned an empty result set (i.e. zero rows). (Query took 0.0010 sec)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "myexcel";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $database);
if (isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen( $file, "r");
while(($fileop = fgetcsv($handle, 3000, ",")) !== false)
{
$id = $fileop[0];
$name = $fileop[1];
$sql = "INSERT INTO csv (id, name) VALUES ('$id', '$name')";
}
if ($sql)
{
echo "OK";
}
}
?>
<html>
<body>
<input type="file" name="file" id="file">
<input type="submit" value="Upload" name="submit">
</body>
</html>
You forgot to query:
$sql = mysqli_query($connection, "INSERT INTO csv (id, name) VALUES ('$id', '$name')");
Add mysqli_query and put your if condition inside while loop.... And i could not see any form tag in your code ??? I have added here with post method
?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "myexcel";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $database);
if (isset($_POST['submit']))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen( $file, "r");
while(($fileop = fgetcsv($handle, 3000, ",")) !== false)
{
$id = $fileop[0];
$name = $fileop[1];
$sql = mysqli_query($connection, "INSERT INTO csv (id, name) VALUES ('$id', '$name')");
if ($sql)
{
echo "Ok. Inserted <br>";
}
}
}
?>
<html>
<body>
<form method="POST"> // add this
<input type="file" name="file" id="file">
<input type="submit" value="Upload" name="submit">
</form>
</body>
</html>

Categories