Hi how to upload multiple image in php with rename and insert databse?
my code is below but not rename and insert 1 rows in datase.
$uploads_dir = 'uploaded/up/';
foreach ($_FILES["layout_plan_no_of_images"]["error"] as $i => $k) {
if ($k == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["layout_plan_no_of_images"]["tmp_name"][$i];
$name = $_FILES["layout_plan_no_of_images"]["name"][$i];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
$sql="INSERT INTO projects (layout_plan_no_of_images)VALUES(':layout_plan_no_of_images')";
$sql_result = $db->queryPrepared($sql, array(
':layout_plan_no_of_images' => $_FILES['layout_plan_no_of_images']['name']
));
Hi try to below code may be help for with rename
foreach($_FILES["layout_plan_no_of_images"]['name'] as $key=>$tmp_name){
$file_name=$_FILES["layout_plan_no_of_images"]["name"][$key];
$file_tmp=$_FILES["layout_plan_no_of_images"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
$filename=basename($file_name,$ext);
$newFileName=(string)$filename.time().".".$ext;
move_uploaded_file($file_tmp=$_FILES["layout_plan_no_of_images"]["tmp_name"][$key],"uploaded/".$newFileName);
$concateFiles .= $comma.$newFileName;
$comma = ',';
}
$sql="INSERT INTO projects (`layout_plan_no_of_images`, `pid`)VALUES($concateFiles)";
$sql_result = $db->queryPrepared($sql, array(
':layout_plan_no_of_images' => $concateFiles,
));
Related
I know this is duplicate question. But I have tried all the answers which I have found on the https://stackoverflow.com/ .
I think in my case I am inserting and updating data if same date match than record will update if not than it will insert.
Below is my file code:
<?php
if ( isset( $_POST['submit'] ) && $_POST['upload-csv'] == 'upload' ) {
$error = array();
$success = array();
$filename = $_FILES['file']['name'];
$filetype = wp_check_filetype( $filename );
if ( $filetype['ext'] == 'csv' && $filetype['type'] == 'text/csv' ) {
$handle = fopen( $_FILES['file']['tmp_name'], "r" );
$row = 0;
$skip_row_number = array("1");
while ( ($data = fgetcsv( $handle, 1000, "," )) !== FALSE ) {
$data = array_map("utf8_encode", $data);
if ($row > 0)
{
$table_name = $wpdb->prefix . 'prayer';
$ipquery = $wpdb->get_results("SELECT * FROM `$table_name` WHERE `date` = '".$data[0]."'");
$query_res = $wpdb->num_rows;
// Check if same date data
if($query_res >=1){
$updateQuery = "UPDATE `$table_name` SET
`date` = '".$data[0]."',
`first_start` = '".$data[1]."',
`first_end` = '".$data[2]."',
`second_start` = '".$data[3]."',
`second_end` = '".$data[4]."',
`third_start` = '".$data[5]."',
`third_end` = '".$data[6]."',
`forth_start` = '".$data[7]."',
`forth_end` = '".$data[8]."',
`five_start` = '".$data[9]."',
`five_end` = '".$data[10]."',
`done` = '".$data[10]."'
WHERE `$table_name`.`date` = '".$data[0]."';";
$up_res = $wpdb->query($updateQuery);
}else{
$query = "INSERT INTO $table_name (date, first_start, first_end, second_start,
second_end, third_start, third_end, forth_start, forth_end, five_start, five_end, done)
VALUES ('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."','".$data[5]."','".$data[6]."','".$data[7]."','".$data[8]."','".$data[9]."','".$data[10]."','".$data[11]."')";
$insert_res = $wpdb->query($query);
}
}
$row++;
}
fclose( $handle );
$success[] = 'Import done.';
} else {
$error[] = 'Please upload CSV file only';
}
}
?>
I have tried the below answer for skip the header:
Skip the first line of a CSV file
Import CSV, exclude first row
skip first line of fgetcsv method in php
Help me sort out this issue.
ParseCSV is latest and easy way to get data from CSV and you can get control of data from CSV easily.
in which you have to add library file as per proper path
e.g. require_once 'parsecsv.lib.php';
After then it return title and data seperately.
$filename = 'abc.csv'; // path of CSV file or after upload pass temp path of file
$csv = new parseCSV();
$csv->auto($filename);
foreach ($csv->titles as $value):
$getcsvtitle[] = // get header in variable
endforeach;
foreach ($csv->data as $key => $row):
//$getdataasperrow = // get data row wise.
endforeach;
ParseCSV return data in array format after just adding library, so you can easily separate header and other data, and compatible to new line and special character as well as i have been always using it as well.
Please refer below link for further detail as well.
ParseCSV GitHub
I am using following script to upload images. Here is the link : http://filer.grandesign.md/
Using this script It's allowing the preview after upload the image. Like bellow image :
You can see that, it's also allowing to delete the Image - See red bucket icon
What I am doing now :
When I upload the image I renamed the uploaded image and save it to database.
The code is bellow :
require_once('class.upload.php');
if(!isset($_FILES['files'])) {
die();
}
$files = array();
foreach ($_FILES['files'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new upload($file);
if ($handle->uploaded) {
$handle->file_new_name_body = 'mpic_list_'.uniqid('', true);
$menu_list_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 360;
$handle->image_y = 240;
$handle->process('images/menu_images/');
$handle->file_new_name_body = 'mpic_small_'.uniqid('', true);
$menu_small_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 100;
$handle->image_y = 65;
$handle->process('images/menu_images/');
$handle->file_new_name_body = 'mpic_large_'.uniqid('', true);
$menu_large_image = $handle->file_new_name_body;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 700;
$handle->image_y = 470;
$handle->process('images/menu_images/');
if ($handle->processed) {
$all_images = $menu_list_image . $menu_small_image . $menu_large_image;
$u_id = (int) $_SESSION['logged_user_id'];
if(!isset($_SESSION['last_id'])) {
// insert upload image section data...
$insert_menu_details = mysqli_query($conn, "INSERT INTO products (p_id) VALUES ('')");
$last_id = mysqli_insert_id($conn);
$insert_upload_image = mysqli_query($conn, "INSERT INTO product_images VALUES ('', '$menu_large_image', '$menu_list_image', '$menu_small_image', '$last_id', '$u_id')");
$_SESSION['last_id'] = $last_id;
} else {
// update upload image section data
$session_last_id = $_SESSION['last_id'];
$update_upload_image = mysqli_query($conn, "INSERT INTO product_images VALUES ('', '$menu_large_image', '$menu_list_image', '$menu_small_image', '$session_last_id', '$u_id')");
}
$handle->clean();
} else {
//echo 'error : ' . $handle->error;
echo 'Error';
}
}
}
What I need :
Now I want to delete my uploaded image. But here is an issue which is : by default this script is deleting the uploaded image using following PHP line :
<?php
if(isset($_POST['file'])){
$file = 'images/menu_images/' . $_POST['file'];
if(file_exists($file)){
unlink($file);
}
}
?>
But I can't delete it because when I upload the image to folder (images/menu_images/) I renamed it to something like that : abedkd12415775554.jpg
My Question is How can I delete my uploaded image using this script ?
You need to return the new images name that you are generating from server scripting like-
In the loop you are executing for inserting filename in database-
$array = array("oldName" => "newName");
echo json_encode($array);
You can also use numeric index if you are using some logic at your javascript end for creating array.
In javascript on delete option you can retrieve the value by using the image name and can perform delete.
check this
$res=mysqli_query("SELECT file FROM tbl_uploads WHERE id=".$_GET['remove_id']);
$row=mysqli_fetch_array($res);
mysqli_query("DELETE FROM tbl_uploads WHERE id=".$_GET['remove_id']);
unlink("uploads/".$row['file']);
Replace Your table and id name
I am uploading a file to mysql database. Now the file contains records of login and logout of users. Below is its structure.
I am using PHP codeigniter to upload that file and insert its data into SQL.
Here date_data is Defined as UNIQUE So that i dont get any duplicate records for same day as it contains information of daily user's login and logout data.
Now in a case where i have uploaded a data of 1st Nov to 10th December. and then again i upload data from 1st December to 1St January i will get an error because it will give error for the duplicate data from 1st Dec and other consecutive days. Is it possible that i can skip the duplicate data and insert the remaining unique data??
As for my current code it stops the execution when it finds duplicate data. i want to insert only that data which is unique.
Below is my code to insert into SQL table:
Controller
public function 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/";
$location = $_FILES['file'];
$new_size = $file_size / 1024; // new file size in KB
$new_file_name = strtolower($file);
$final_file = str_replace(' ', '-', $new_file_name); // make file name in lower case
if (move_uploaded_file($file_loc, $folder . $final_file))
{
$handle = fopen($folder.$final_file, "r") or die("file cannot open");
if ($handle) {
while (($line = fgets($handle)) !== false)
{
$lineArr = explode("\t", "$line");
$result = $this->attendance_m->insert_file_content($lineArr) ;
}
if (fclose($handle)) {
$this->alert('successfully uploaded', 'admin/attendance.php?success');
redirect('admin/attendance');
}
}
else{
echo "file cannot open";
}
}
}
The Model:
public function insert_file_content($lineArr)
{
$data = array(
'emp_id' => $lineArr[0],
'date_data' => $lineArr[1],
'abc' => $lineArr[2],
'def' => $lineArr[3],
'entry' => $lineArr[4],
'ghi' => $lineArr[5],
);
$this->db->insert('daily_data2', $data);
}
To ignore a duplicate record on insert
$data = array(
'emp_id' => $lineArr[0],
'date_data' => $lineArr[1],
'abc' => $lineArr[2],
'def' => $lineArr[3],
'entry' => $lineArr[4],
'ghi' => $lineArr[5],
);
$sql = "INSERT IGNORE INTO `daily_data2`
(`emp_id`,`date_data`,`abc`,`def`,`entry`,`ghi`)
VALUES
(?,?,?,?,?,?)";
$this->db->query($sql, $data);
You could also try out this way
$result = $this->db->get_where('daily_data2', array('date_data' => $data['date_data'));
if(count( $result->result_array() ) < 1)
{
//insert a new record
}
I am build uploader images and store it into database, I already can upload many images to folder, but I can't insert all images name that uploaded, and I don't know how to insert into database, first I have put commend on my code below when error occur, second I don't know the query to put it in database if the image count is different e.g 1-10 images, last question, if I do query "SELECT id..." and I want to return it, is there method to return it into string or int? If I use row() it will return stdClass object. please help me,
below is my code:
controller :
$this->load->library("myupload", "form_validation");
$this->load->model("testModel");
$barangImage = array();
if($this->input->post("formSubmit")) {
$this->form_validation->set_rules("nama", "Nama", "required|trim");
if($this->form_validation->run()) {
$insertData = array(
"nama" => $this->input->post("nama")
);
if($id = $this->testModel->add($insertData)) {
//print_r($id);
if(isset($_FILES) && $image = $this->myupload->uploadFile($_FILES)) {
//$image here is already fill with all images name
if(isset($image["error"]) && $image["error"]) {
echo $image["error"];
}else {
foreach($image as $img) {
$barangImage = array(
"gambar" => $img,
"barangid" => $id
);
}
//but when i put into barangImage,
//it only stored last image name
print_r($barangImage);
//output `Array ( [gambar] => 2.JPG [barangid] => Array ( [id] => 52 ) )`
}
}
if($id = $this->testModel->add_images($barangImage)) {
echo "SUCCESS !!!";
}else {
echo "FAIL INSERT IMAGES!!!";
}
}else {
echo "FAIL INSERT DATA NAMA";
}
}else {
echo "FAIL VALIDASI RUN";
}
}
model :
public function add($newData){
$this->db->insert("cobabarang", $newData);
$nama = $newData["nama"];
$id = $this->db->query("SELECT id FROM cobabarang WHERE nama = \"$nama\"");
return $id->row_array();
}
public function add_images($newImage) {
//$this->db->insert("cobagambar", $newImage);
$id = $newImage["barangid"]["id"];
$gambar = $newImage["gambar"];
$this->db->query("INSERT INTO cobagambar(barangid, gambar1) VALUES($id, \"$gambar\")");
}
there is an error here:
foreach($image as $img)
{
$barangImage = array(
"gambar" => $img,
"barangid" => $id
);
}
change the $barangImage to $barangImage[]
when you put the images into database i suggest that using json_encode($barangImage), and then json_decode($images-json-string) when you going to use the images.
There is something wrong with your foreach loop
foreach($image as $img) {
$barangImage = array(
"gambar" => $img //might be img['img'] I guess $img is again an array...you hvae to check that
"barangid" => $id //might be $img['id']check on this too..will be $img['id'] I guess
);
}
My guess is that $img is again an array with some keys. You really need to check on that And you can directly call the insert function in that foreach loop itself like this,
foreach($image as $img) {
$barangImage = array(
"gambar1" => $img['img'], //I guess $img is again an array...you hvae to check that
"barangid" => $img['id'] //check on this too..will be $img['id'] I guess
);
$id = $this->testModel->add_images($barangImage));
}
NOTE: The keys in your array barangImage must be column name in the table. i.e
gambar1 and barangid will be your column names. so you can directly use codeIgniter's active records.
Just change your add_images function
public function add_images($newImage) {
$this->db->insert("cobagambar", $newImage);
}
the method I have is I create three input files which will be posted to three different column in database table.
Heres my parameter:
$additional_comments=$_POST['additional_comments'];
$image_one = $_FILES['image_one']['type'];
$image_two = $_FILES['image_two']['type'];
$image_three = $_FILES['image_three']['type'];
if($image=="image/jpeg" || $image=="image/jpg" || $image=="image/gif" || $image=="image/png")
{
$gambar_satu = $foldername . basename($_FILES['image_one']['name']);
$gambar_dua = $foldername . basename($_FILES['image_two']['name']);
$gambar_tiga = $foldername . basename($_FILES['image_three']['name']);
if ( move_uploaded_file
($_FILES['image']['tmp_name'], $gambar_satu)
($_FILES['image']['tmp_name'], $gambar_dua)
($_FILES['image']['tmp_name'], $gambar_tiga)
)
{
$stmt = $mysqli->prepare
("INSERT INTO table...
In the if (move_uploaded_file... I am trying to insert three paramater there which they are $gambar_satu, $gambar_dua, $gambar_tiga.
My question is how is the correct way to do this? Thanks in advance.
Quoting directly from the php website
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
Hope it helps!