I am using the below code for importing the excel sheet and inserting the data into the database and it's working. There is no issue with it.
Now, I have a column name called content. I am uploading the content in it. so below is the example of the content.
Now after importing the data I am getting the output like. so it's removing the strong part and spacing etc.
I am using the rich text editor and I am displaying the data in it.
function listImport($pdo){
if($_FILES["emplist"]["name"] != '')
{
$allowed_extension = array('csv');
$file_array = explode(".", $_FILES["emplist"]["name"]);
$file_extension = end($file_array);
if(in_array($file_extension, $allowed_extension))
{
$file_name = time() . '.' . $file_extension;
move_uploaded_file($_FILES['emplist']['tmp_name'], $file_name);
$file_type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file_name);
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($file_type);
$spreadsheet = $reader->load($file_name);
unlink($file_name);
$data = $spreadsheet->getActiveSheet()->toArray();
$isheader = 0;
foreach($data as $row)
{
if($isheader > 0) {
$insert_data = array(
':name' => $row[0],
':email' => $row[1],
':content' => $row[2]
);
$query = "INSERT INTO `employee`(`name`, `email`, `content`) VALUES (:name,:email,:content)";
$statement = $pdo->prepare($query);
$statement->execute($insert_data);
}
else {
$isheader = 1;
}
} // foreach
$message = '<div class="alert alert-success">Data Imported Successfully</div>';
} //in_array
else
{
$message = '<div class="alert alert-danger">Only .csv file allowed</div>';
}
}
else
{
$message = '<div class="alert alert-danger">Please Select File</div>';
}
echo $message;
}
Related
I am trying to read CSV file using fgetcsv() php function but It doesn't fetch detail as it supposed to be. I found out that the CSV file is cluttered and has multiple irrelevant commas in starting and in-between. How do I make this CSV cleaner?
I used str_replace() php function to remove triplets of commas but the commas in starting are still giving me a problem. I tried ltrim() also but that didn't work too.
<?php
$file = "grid.csv";
$s = file_get_contents($file);
$s = str_replace(",,,", "", $s);
//$s = ltrim($s,",");
$f = "grid1.csv";
$handle = fopen($f, "w");
fwrite($handle, $s);
?>
I expect the output of this code to be a clean csv file. But I get multiple commas in starting now also in the new file.
This is the Main Code where I was trying to read the file using fgetcsv().
if(isset($_POST["submit"])){
echo "in submit</br>";
if($_FILES['csv_info']['name']){
echo "some file</br>";
$filename = explode(".", $_FILES['csv_info']['name']);
if(end($filename) == 'csv'){
echo "file is csv</br>".$_FILES['csv_info']['tmp_name'];
$handle = fopen($_FILES['csv_info']['tmp_name'],"r");
$sid = 0;
//$query = "select exists(select 1 from tblMarks)";
//$choice = mysqli_query($conn, $query);
while($data = fgetcsv($handle)){
if($sid == 0){
$sid = $sid + 1;
continue;
}
//echo $data;
$name = mysqli_real_escape_string($conn, $data[0]);
$physics = mysqli_real_escape_string($conn, $data[1]);
$maths = mysqli_real_escape_string($conn, $data[2]);
$chemistry = mysqli_real_escape_string($conn, $data[3]);
$bio = mysqli_real_escape_string($conn, $data[4]);
$sst = mysqli_real_escape_string($conn, $data[5]);
echo "</br>inserting sid".$sid." name=".$name." physics=".$physics." maths=".$maths." chemistry=".$chemistry." bio=".$bio." sst=".$sst."</br>";
//$query = "insert into tblMarks (sid, name, physics, maths, chemistry, bio, sst) values ('$sid', '$name', '$physics', '$maths','$chemistry','$bio','$sst') on duplicate key update name = '$name', physics = '$physics',maths = '$maths', chemistry = '$chemistry', bio = '$bio', sst ='$sst'";
//mysqli_query($conn, $query);
$sid = $sid + 1;
}
fclose($handle);
}
else{
$message = '<label class="text-danger">Please Select CSV File Only</lable>';
}
}
else{
$message = '<label class="text-danger">Please Select File</label>';
}
}
The output was this:
OUTPUT
here is the correct method to read CSV file row by row. There are many rows in the CSV files which have blank values, to remove theme array_filter has been used.
$temp = array();
if (($h = fopen("grid.csv", "r")) !== FALSE)
{
// Convert each line into the local $data variable
while (($data = fgetcsv($h, 1000, ",")) !== FALSE)
{
$data = array_filter($data);
if(count($data) > 0){
$temp[] = $data;
}
}
fclose($h);
}
//Write csv file
$fp = fopen('grid1.csv', 'w');
foreach ($temp as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
please help guys i have code for inserting name and etc.. and for inserting a image i cant combine the codes
here is the ouput in phpmyadmin i only insert one value thou...
thanks for your help guys
<---!THIS CODE BELOW IT INSERT ID,NAME AND ETC --->
<?php
require 'db.php';
$message = '';
$Error = '';
if (isset ($_POST['Attendee_id']) &&
isset($_POST['RFID_number']) &&
isset($_POST['Attendee_Name']) &&
isset($_POST['CourseOrDepartment']) &&
isset ($_POST['Status']) ) {
$Attendee_id = $_POST['Attendee_id'];
$RFID_number = $_POST['RFID_number'];
$Attendee_Name = $_POST['Attendee_Name'];
$CourseOrDepartment = $_POST['CourseOrDepartment'];
$Status = $_POST['Status'];
$sql = 'INSERT INTO tbl_listofregister(Attendee_id,
RFID_number,Attendee_Name,CourseOrDepartment,Status)
VALUES(:Attendee_id,
:RFID_number,:Attendee_Name,:CourseOrDepartment,:Status)';
$statement = $connection->prepare($sql);
if ($statement->execute([':Attendee_id' => $Attendee_id, ':RFID_number' =>
$RFID_number,':Attendee_Name' => $Attendee_Name,':CourseOrDepartment' =>
$CourseOrDepartment,':Status' => $Status])) {
$message = 'DATA INSERTED SUCCESSFULLY';
}
else
{
$Error = "ID SHOULD BE UNIQUE";
}
}
?>
<---! HERE IS FOR IMAGE --->
<?php
$msg = '';
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_FILES['Image']['tmp_name'];
$img = file_get_contents($image);
$con = mysqli_connect('localhost','root','','dbattendancelibrary') or
die('Unable To connect');
$sql = "insert into tbl_listofregister (image) values(?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt, "s",$img);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check==1){
$msg = 'Image Successfullly UPloaded';
}else{
$msg = 'Error uploading image';
}
mysqli_close($con);
}
?>
This would combine the two inserts into one action. But I would advise against storing the images in the db. Store the path relative to your site of the image instead.
<?php
require 'db.php';
$message = '';
$Error = '';
if(isset($_POST['Attendee_id']) &&
isset($_POST['RFID_number']) &&
isset($_POST['Attendee_Name']) &&
isset($_POST['CourseOrDepartment']) &&
isset($_POST['Status']) &&
isset($_FILES['Image']['tmp_name']) &&
$_SERVER['REQUEST_METHOD']=='POST') {
$Attendee_id = $_POST['Attendee_id'];
$RFID_number = $_POST['RFID_number'];
$Attendee_Name = $_POST['Attendee_Name'];
$CourseOrDepartment = $_POST['CourseOrDepartment'];
$Status = $_POST['Status'];
$image = $_FILES['Image']['tmp_name'];
$img = file_get_contents($image);
$sql = 'INSERT INTO tbl_listofregister(
Attendee_id,
RFID_number,
Attendee_Name,
CourseOrDepartment,
Status,
image)
VALUES(:Attendee_id,
:RFID_number,
:Attendee_Name,
:CourseOrDepartment,
:Status,
:Image)';
$statement = $connection->prepare($sql);
if($statement->execute(
[':Attendee_id' => $Attendee_id,
':RFID_number' => $RFID_number,
':Attendee_Name' => $Attendee_Name,
':CourseOrDepartment' => $CourseOrDepartment,
':Status' => $Status,
':Image' => $img]
)) {
$message = 'DATA INSERTED SUCCESSFULLY';
} else {
$Error = "ID SHOULD BE UNIQUE";
}
}
?>
$Attendee_id = $_POST['Attendee_id'];
$RFID_number = $_POST['RFID_number'];
$Attendee_Name = $_POST['Attendee_Name'];
$CourseOrDepartment = $_POST['CourseOrDepartment'];
$Status = $_POST['Status'];
After these lines , you can add this line for an img
move_uploaded_file($_FILES['file']['tmp_name'], "filename/".$_FILES['file']['name']);
Then, add it in the query as ( $_FILES['file']['name'] ).
in HTML file write this line ( ).
I hope it's work well <3
I try to understand how to use multiple uploads in PDO.
So I have my post.php:
$database = new Database();
$db = $database->getConnection();
$media = new Media($db);
if($_POST){
$image = !empty($_FILES["image"]["name"]) ? sha1_file($_FILES['image']['tmp_name']) . "-" . time() . "-" . basename($_FILES["image"]["name"]) : "";
$media->image = $image;
if ($media->create()) {
echo $media->uploadPhoto();
$_POST=array();
}
}
<input name="image[]" type="file" />
And my media.php with pdo query and some upload validations:
public $image;
public $created;
public function create(){
//write query
$query = "INSERT INTO " . $this->table_name . "
SET image=:image,
created=:created";
$stmt = $this->conn->prepare($query);
$this->image=htmlspecialchars(strip_tags($this->image));
$stmt->bindParam(":image", $this->image);
if($stmt->execute()){
return true;
}
print_r($stmt->errorInfo());
return false;
}
function uploadPhoto(){
$result_message="";
if(!empty($_FILES["image"]["tmp_name"])){
$target_directory = "../uploads/";
$target_file = $target_directory . $this->image;
$file_type = pathinfo($target_file, PATHINFO_EXTENSION);
$file_upload_error_messages="";
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check!==false){
}else{
$file_upload_error_messages.="<div></div>";
}
$allowed_file_types=array("jpg", "JPG", "jpeg", "JPEG", "png", "PNG", "gif", "GIF");
if(!in_array($file_type, $allowed_file_types)){
$file_upload_error_messages.="<div></div>";
}
if(file_exists($target_file)){
}
if($_FILES['image']['size'] > (10485760)){
$file_upload_error_messages.="<div></div>";
}
if(!is_dir($target_directory)){
mkdir($target_directory, 0777, true);
}
if(empty($file_upload_error_messages)){
if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)){
}else{
$result_message.="<div></div>";
}
}
else{
$result_message.="{$file_upload_error_messages}";
}
}
return $result_message;
}
So I need to store the values in different mysql records and upload them all to the server.
What is the best way to do this and where to place the foreach?
I struggle with the right place of the foreach ...
$x=0;
foreach ( $_FILES['image']['name'] AS $key => $value ){
// ...
$x++;
}
so if this is your foreach loop and you want to insert different records for each uploaded file then use mysqli_multi_query
$x=0;
$query = "";
foreach ( $_FILES['image']['name'] AS $key => $value ){
$query .= 'insert into tableName (col1,col2,col3,image)VALUES("a","b","c","'.$value.'");';
$x++;
}
$query = rtrim($query,";");
mysqli_multi_query($connectionObj,$query);
Your query will look somthing like this
insert into tableName (col1,col2,col3,image)VALUES("a","b","c","a.jpg");
insert into tableName (col1,col2,col3,image)VALUES("a","b","c","b.jpg");
I am using the following to upload CSV to a table in MYSQL database.
Question: How do I bypass the 1st field? - as in ignore the header - which is currently being saved in my table?
Code:
<?php
/********************************/
/* Code at http://legend.ws/blog/tips-tricks/csv-php-mysql-import/
/* Edit the entries below to reflect the appropriate values
/********************************/
$databasehost = "localhost";
$databasename = "test";
$databasetable = "sample";
$databaseusername ="test";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "filename.csv";
/********************************/
/* Would you like to add an ampty field at the beginning of these records?
/* This is useful if you have a table with the first field being an auto_increment integer
/* and the csv file does not have such as empty field before the records.
/* Set 1 for yes and 0 for no. ATTENTION: don't set to 1 if you are not sure.
/* This can dump data in the wrong fields if this extra field does not exist in the table
/********************************/
$addauto = 0;
/********************************/
/* Would you like to save the mysql queries in a file? If yes set $save to 1.
/* Permission on the file should be set to 777. Either upload a sample file through ftp and
/* change the permissions, or execute at the prompt: touch output.sql && chmod 777 output.sql
/********************************/
$save = 1;
$outputfile = "output.sql";
/********************************/
if(!file_exists($csvfile)) {
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$con = #mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
$lines = 0;
$queries = "";
$linearray = array();
foreach(split($lineseparator,$csvcontent) as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto)
$query = "insert into $databasetable values('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
$queries .= $query . "\n";
#mysql_query($query);
}
#mysql_close($con);
if($save) {
if(!is_writable($outputfile)) {
echo "File is not writable, check permissions.\n";
}
else {
$file2 = fopen($outputfile,"w");
if(!$file2) {
echo "Error writing to the output file.\n";
}
else {
fwrite($file2,$queries);
fclose($file2);
}
}
}
echo "Found a total of $lines records in this csv file.\n";
?>
I has been did the same purpose at last week. Please refer this code. It may be help you.
if (isset($_POST['submit'])) {
//Path of Uploading file
$target = "upload_files/results/";
$filename = $_FILES['upload_result']['name'];
if(file_exists($target.$filename)) {
unlink($target.$filename);
}
move_uploaded_file($_FILES['upload_result']['tmp_name'], $target.$filename);
//Store the Detail into the Master table...[class_master]
$new_master = mysql_query("INSERT INTO result_master(classname,sectionname,examname,filename) Values('$class','$section','$examname','$filename')");
$filename1 = explode(".",$filename);
$file = preg_replace("/[^a-zA-Z0-9]+/", "", $filename1[0]);
// get structure from csv and insert db
ini_set('auto_detect_line_endings',TRUE);
$handle = fopen($target.$filename,'r');
// first row, structure
if ( ($data = fgetcsv($handle) ) === FALSE ) {
echo "Cannot read from csv $file";die();
}
$fields = array();
$field_count = 0;
for($i=0;$i<count($data); $i++) {
$f = trim($data[$i]);
if ($f) {
// normalize the field name, strip to 20 chars if too long
$f = substr(preg_replace ('/[^0-9a-z]/', '_', $f), 0, 20);
$field_count++;
$fields[] = $f.' VARCHAR(50)';
}
}
$drop = mysql_query("Drop table IF EXISTS $file;");
$sql = "CREATE TABLE $file (" . implode(', ', $fields) . ')';
echo $sql . "<br /><br />";
$db = mysql_query($sql);
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
$fields = array();
for($i=0;$i<$field_count; $i++) {
$fields[] = '\''.addslashes($data[$i]).'\'';
}
$sql = "Insert into $file values(" . implode(', ', $fields) . ')';
echo $sql;
$db = mysql_query($sql);
}
fclose($handle);
ini_set('auto_detect_line_endings',FALSE);
}
You either assume that there is ALWAYS a header, or that any header will be commented by some character, I will show you the first. You can just wrap the insertion lines in a conditional block to check for this.
if( $lines != 0 ) // or $linemysql[0][0] == '#' (assuming # is a "comment")
{
if($addauto)
$query = "insert into $databasetable values('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
}
That being said, PLEASE! Do not ever use the code you posted in any internet facing application, you are putting user-provided data directly into the database, so it would be trivial to make a csv file containing SQL injection attack and change your mysql password, steal your data, kill your cat or delete everything. You should also check the number of fields and such, what happens if the csv contains lines without the correct number of fields ?
Read up on http://en.wikipedia.org/wiki/SQL_injection
and also http://php.net/PDO
Use this code in removing the header in the csv file and upload the data in the database:
$header= 1;
if (($handle = fopen("data.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($header== 1)
{
$header++;
continue;
}
//do your code here saving into the database
}
fclose($handle);
}
This code is to update database. it updates everything even uploads image sucessfully but after image upload the whole page gets blank and only "Array()" is displayed at top. Why is that?
<?php
if(!isset($_GET["prid"])){
header("Location: prjedit.php");
}
else {
$prid = intval($_GET["prid"]);
$sqlprj = "SELECT * FROM projects WHERE id = ? LIMIT 1";
$statement = $db->prepare($sqlprj);
$statement->execute(array($prid));
$project = $statement->fetchObject();
//submitted form
if( (isset($_POST["title"])) && (isset($_POST["details"])) ) {
$title = $_POST['title'];
$desc = $_POST['descr'];
$details = $_POST['details'];
if(!empty($_FILES['image']['name'])) {
//update image
$file = basename($_FILES['image']['name']);
$dir = "projects/";
$target_path = $dir . basename($_FILES['image']['name']);
$tempname = $_FILES['image']['tmp_name'];
if(!file_exists($target_path)) {
if(move_uploaded_file($tempname, $target_path)) {
$sqlimg = "UPDATE projects SET image = ? WHERE id = ?";
$statement = $db->prepare($sqlimg);
$statement->execute(array($file, $prid));
if($statement->rowCount() > 0) {
try {
chdir('./projects/');
unlink($project->image);
chdir('..');
}
catch (Exception $e) {
$message = "Sorry image delete failed ";
echo $e->getMessage();
}
}
else {
die ($db->errorInfo());
}
}
else {
$message = "Sorry Image update failed";
}
}
else {
$message = "Sorry this image already exists but text";
}
}
// update project texts
$sqlupd = "UPDATE projects SET title = ?, descinfo = ?, details = ? WHERE id = ?";
$statement = $db->prepare($sqlupd);
$statement->execute(array($title, $desc, $details, $prid));
if($statement->rowCount()) {
$message = " Saved successfully";
}
else {
die($db->errorInfo());
}
}
}
?>
Looking at Pdo::codeInfo documentation, it returns an array.
When you write die($db->errorInfo()); it will try to display this array.
As suggested by the documentation itself, you could try print_r($db->errorInfo()); die; and see what happens.