Try uploading csv file to mysql using php and mysql - php

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>

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>

php sql code not inserting into db

I'm new to php and a complete noob. I used following code to insert some files to my db.
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql = "INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
//mysql_query($sql, $conn);
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
Though this save the file in upload folder, it does not insert anything into the data base. No matter how many times its uploaded database remain empty. It doesn't show any error either.
My config.php file is
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbtuts";
$conn = new mysqli($dbhost, $dbuser, $dbpass);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
HTML part
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
No DB is selected
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbtuts";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname); // <--- here select db first
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Then use
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql = "INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
if($conn->query($sql)) {
echo "Success";
} else {
echo "Failed. Error: ".$conn->error;
}
?>
<script>
alert('successfully uploaded');
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
I think, your sql can not get variable
You try to write like that:
$sql = "INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
Try this
$sql = "INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
mysqli_query($conn,$sql);

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.

importing csv file to database using 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";
}
}

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