I have coded this far but the only issue i have is that i can't save multiple rows for the same user id when the user uploads several pictures. the code works perfectly fine, I mean the multiple files gets inserted into the file system folder/root directory but the reference in the database doesn't quit work. It only inserts the first file uploaded image not the the second file upload.
Here is my code:
<?php
if(isset($_POST['go'])) {
if(isset($_FILES['file_array'])){
$errors= array();
foreach($_FILES['file_array']['tmp_name'] as $key => $tmp_name ) {
$user = $_SESSION['user_id'];
$file_name = $key.$_FILES['file_array']['name'][$key];
$file_size =$_FILES['file_array']['size'][$key];
$file_tmp =$_FILES['file_array']['tmp_name'][$key];
$file_type=$_FILES['file_array']['type'][$key];
}
$extensions = array("jpeg","jpg","png");
$file_ext=explode('.',$_FILES['file_array']['name'][$key]);
$file_ext=end($file_ext);
$file_ext=strtolower(end(explode('.',$_FILES['file_array']['name'][$key])));
if(in_array($file_ext,$extensions ) === false) {
$errors[]="extension not allowed";
}
if($_FILES['file_array']['size'][$key] > 2097152) {
$errors[]='File size must be less tham 2 MB';
}
$query = array();
$myarray = '';
if(is_array($query)) {
foreach ($query as $row) {
$query[] = '('.$row['ID'].',"'.$row['FILE_NAME'].'", "'.$row['FILE_TYPE'].'", "'.$row['FILE_SIZE'].'")';
}
}
$dir = "users_data/profile/users_posted_data/";
if(empty($errors)==true) {
if(is_dir($dir)==false){
mkdir("$dir/", 0700);
}
if(is_dir("$dir/".$file_name)==false) {
move_uploaded_file($file_tmp,"$dir/".$file_name);
} else {
$new_dir="$dir/".$file_name.time();
rename($file_tmp, "$dir/".$file_name);
}
$query_run = mysqli_query($mysqli, 'INSERT INTO table (ID, FILE_NAME,FILE_SIZE, FILE_TYPE) VALUES '.implode(',', $query));
} else {
print_r($errors);
}
if(empty($error)) {
echo "Success";
}
}
}
?>
You are trying to iterate over an empty array. Not sure what you were actually trying to do but this will do nothing.
$query = array(); // init array
$myarray = '';
if(is_array($query)) { // test that its an array which it obviously is see 2 lines previous
foreach ($query as $row) { // iterate over empty array
// add to the array we are **not** iterating over
$query[] = '('.$row['ID'].',"'.$row['FILE_NAME'].'", "'.$row['FILE_TYPE'].'", "'.$row['FILE_SIZE'].'")';
}
}
Related
I have noticed that if a cell is empty phpexcel gives it a null value. Is there a way i can replace the null value with any empty string before i loop through the array and store into the database. Below is my code and i am using the codeigniter framework.
public function import(){
$id = $this->session->userdata('company_id');
$directoryname = get_company_full_name($id);
if (!is_dir(FCPATH.'assets/customer_documents/Databases/'.$directoryname)) {
mkdir(FCPATH.'assets/customer_documents/Databases/'.$directoryname, 0777, TRUE);
}
$database_name = $this->input->post('database_name');
// $data['addressbook'] = $this->csv_model->get_addressbook($id);
$data['errors'] = ''; //initialize upload error array to empty
$config['upload_path'] = FCPATH.'assets/customer_documents/Databases/'.$directoryname;
$config['allowed_types'] = '*';
$config['max_size'] = '';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$data['errors'] = $this->upload->display_errors();
$data['databases'] = $this->database->get_databases($id);
$this->session->set_flashdata($data);
redirect(base_url().'Databases');
} else {
$file_data = $this->upload->data();
$file_ext = $file_data['file_ext'];
// use custom function to determine if filetype is allowed
if (allow_csv_type($file_ext))
{
$file_path = FCPATH.'assets/customer_documents/Databases/'.$directoryname. '/' .$file_data['file_name'];
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file_path);
$date_uploaded = date("Y-m-d H:i:s");
if ($objPHPExcel) {
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
// array_shift($arr_data); // removes the 1st/header element
//store the database name and details
$database_data = array(
'db_name'=>$database_name,
'company_id' => $id,
'deleted' => 0,
'date_uploaded'=> $date_uploaded
);
$this->database->insert_db($database_data);
$database_id = $this->db->insert_id();
foreach ($arr_data as $row) {
$insert_data = array(
'company_id' => $this->session->userdata('company_id'),
'number'=>$row['A'],
'province'=>$row['B'],
'district'=>$row['C'],
'ward'=>$row['D'],
'farming_type'=>$row['E'],
'commodity'=>$row['F'],
'database_name'=>$database_name,
'db_id' =>$database_id,
'deleted' => 0,
'date_uploaded'=>$date_uploaded
);
$this->database->insert_csv($insert_data, $id);
}
log_message('info', '*****************************Customer with the ID: '.$this->session->userdata('company_id').' and name: '.get_company_full_name($this->session->userdata('company_id')).' uploaded a csv database. The uploder phone number: '.$this->session->userdata('phone').' The database ID: '.$database_id.' The database name: '.$database_name.'*****************************');
$this->session->set_flashdata('success', 'Data Imported Succesfully');
redirect(base_url().'Databases');
} else{
$data['errors'] = "Error occured";
$data['page_class'] = 'Databases-page';
$data['title'] = 'Databases';
$data['content_view'] = 'Databases/index';
$this->template->admin_template($data);
}
}
else {
$this->session->set_flashdata('errors','File type is not allowed!');
redirect('Databases');
}
}
}
}
I am just looking for a way i can add empty sting values on the empty cells that are coming with null values.
Just use a simple array modifier before it reaches PHPExcel.
If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.
$replacements = array(
'search1' => 'replace1',
'search2' => 'replace2',
'search3' => 'replace3'
);
foreach ($a as $key => $value) {
if (isset($replacements[$value])) {
$a[$key] = $replacements[$value];
}
}
See: https://stackoverflow.com/a/32321702/4272537
I'm having trouble figuring out why it is that when an image size is too big, I get the error 'Invalid File Type' 'Uploaded file is not an image' instead of getting 'File is too big' (The image validation/upload script I didn't completely write myself- I found the code and made it work with for my needs). Everything else seems to work fine except for this. Also I get the following warning
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\minnow\includes\create-post.php on line 75
Here is my code
<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
if( empty($_FILES[$image]['name']) ){
$has_image = 0;
}else{
$has_image = 1;
}
$postEmpty = 0;
$imageError = 0;
if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
}
// validate post
if( $postEmpty == 0 && !empty($body) ){
$cleanBody = clean_input($body);
}
// validate image (if any)
if( $has_image == 1 ){
//check if directory exist if not create it
if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
}
if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
}
//Set file upload path
$path = "../users/user_".$user_id."/posts/"; //with trailing slash
//Set max file size in bytes
$max_size = 2000000;
//Set default file extension whitelist
$whitelist_ext = array('jpeg','jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');
// Create an array to hold any output
$errors = array();
// Get filename
$file_info = pathinfo($_FILES[$image]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$errors[] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
$errors[] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$image]["size"] > $max_size) {
$errors[] = "File is too big";
}
//If $check image is set as true
if ( !getimagesize($_FILES[$image]['tmp_name']) ) {
$errors[] = "Uploaded file is not a valid image";
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
}
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}else {
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
}
}
// if no errors:
// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){
$query = "INSERT INTO posts
(user_id, body, image, has_image, date)
VALUES
('$user_id', '$body', '$newname', '$has_image', now())";
}else{
$query = "INSERT INTO posts
(user_id, body, has_image, date)
VALUES
('$user_id', '$body', '$has_image', now())";
}
$result = $db->query($query);
// send response
//check to make sure the user was added
if( $db->affected_rows == 1 ){
$user_id = $_SESSION['user_id'];
$post_id = $db->insert_id;
$query = "SELECT post_id, body, image, has_image
FROM posts
WHERE post_id = $post_id
LIMIT 1";
$result = $db->query($query);
if($result->num_rows == 1){
$row = $result->fetch_assoc();
}
$queryuser = "SELECT *
FROM users
WHERE user_id = $user_id
LIMIT 1";
$resultuser = $db->query($queryuser);
if($resultuser->num_rows == 1){
$rowuser = $resultuser->fetch_assoc();
}
if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }
if($row['has_image'] == 1){
$data = "<article class='post'><div class='post-head cf'><a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a><a href='' class='username'>".$rowuser['username']."</a></div><img src='users/user_".$rowuser['user_id']."/posts/".$row['image']."' alt=''><div class='post-body'><div class='post-options'><a class='likes' href=''>156 likes</a></div><p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p><hr /><div class='cf'><a class='like hide-text' href='javascript:;'>Like This Post</a><form action='' class='comment'><input type='text' placeholder='Add a comment'></form></div></div></article>";
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}else{
$data = "<article class='post no-img'><div class='post-head cf'><a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a><a href='' class='username'>".$rowuser['username']."</a></div><div class='post-body'><p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p><div class='post-options'><a class='likes' href=''>1 like</a></div><hr /><div class='cf'><a class='like hide-text' href='javascript:;'>Like This Post</a><form action='' class='comment'><input type='text' placeholder='Add a comment'></form></div></div></article>";
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}
}else{
$errors[] = "Server Error!";
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
}
die();
It could be that the file was just not uploaded to the server.
Check $_FILES[$image]['error'] to see what may have gone wrong.
Refer to the error messages here.
Edit: After these lines:
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
Do this:
// check for error greater than zero
if($_FILES[$image]['error'] > 0) {
// something went wrong with the upload, handle the error
echo $_FILES[$image]['error']; exit; // as an example to find out what the error was
}
Then refer to http://php.net/manual/en/features.file-upload.errors.php to find out the reason.
My codes multiple image upload and update mysql db but one problem if id=1 It's working multiple image uploading and update.else It's not working and white page.
tables 2
musteri_soru and musteri_cevap
is updating musteri_cevap in colon resim
controller code:
function duzenle($no)
{
if($_POST)
{
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no,$arr1);
if($_FILES){
$dizin= "../upload/form_cevap/";
$dosya_sayi=count($_FILES['cevap']['name']);
for($i=0;$i<=$dosya_sayi;$i++){
$isim= md5(uniqid(rand()));
if(!empty($_FILES['cevap']['name'][$i])){
move_uploaded_file($_FILES['cevap']['tmp_name'][$i],"./$dizin/$isim{$_FILES['cevap']['name'][$i]}");
$arr['resim']= $dizin.$isim.$_FILES['cevap']['name'][$i];
}
$approve[] = $arr['resim'];
$it = $approve;
print_r($approve);
foreach($it as $n => $c):
/* $deneme = $this->form_duzenle_model->cevapDuzenle($n,$c); */
endforeach;
}
}
redirect('form_duzenle/', 'refresh');
}else{
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik'=>$veri->baslik,
'veri' =>$veri,
'cevap' =>$veri2
);
$this->bc->addCrumb($veri->baslik,'form_duzenle/duzenle/'.$veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle',$data);
}
}
Models code :
function duzenle($no,$data)
{
$this->db->update($this->tablo,$data, array('no' => $no));
}
function cevapDuzenle($n,$dat)
{
$data = array('resim' => $dat);
$this->db->update($this->ctablo,$data, array('soru_no' => $n));
}
My Tables
enter link description here
To be honest, I'm not quite sure how your upload was working as the $_FILES array shouldn't be nesting the uploads in the way you've shown above.
I'm not saying this will definitely work but it should do:
function duzenle($no)
{
//I would possible look at using the Form_validation Library here
if (empty($_POST)) {
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no, $arr1);
if (!empty($_FILES)) {
$dizin = "../upload/form_cevap/";
foreach ($_FILES as $name => $file) {
//If there is an error there isn't any reason to try and upload this file
if ($file['error'] !== 0) {
continue;
}
$name = $file['name'];
$isim = md5(uniqid(rand()));
move_uploaded_file($file['tmp_name'], "./$dizin/$isim$name");
$arr['resim'] = $dizin . $isim . $name;
//Not sure what's going on here so I haven't changed it
$approve[] = $arr['resim'];
$it = $approve;
print_r($approve);
foreach ($it as $n => $c):
/* $deneme = $this->form_duzenle_model->cevapDuzenle($n,$c); */
endforeach;
}
}
redirect('form_duzenle/', 'refresh');
}else {
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik' => $veri->baslik,
'veri' => $veri,
'cevap' => $veri2
);
$this->bc->addCrumb($veri->baslik, 'form_duzenle/duzenle/' . $veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle', $data);
}
}
Hope this helps!
Check your for loop,
$dosya_sayi=count($_FILES['cevap']['name']);
for($i=0;$i<=$dosya_sayi;$i++)
for loop condition should be $i < $dosya_sayi as array index always starts from 0.
So correct for loop is
for($i=0;$i<$dosya_sayi;$i++)
I solved the problem.Duzenle codes on change the bottom code.
function duzenle($no)
{
if($_POST)
{
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no,$arr1);
$cevaplar = $this->form_duzenle_model->cevapListe($no)->result_array();
if($_FILES){
$dizin= "../upload/form_cevap/";
foreach($cevaplar AS $cevap){
$i = $cevap['no'];
$isim= md5(uniqid(rand()));
if(!empty($_FILES['cevap']['name'][$i])){
move_uploaded_file($_FILES['cevap']['tmp_name'][$i],"./$dizin/$isim{$_FILES['cevap']['name'][$i]}");
$arr['resim']= $dizin.$isim.$_FILES['cevap']['name'][$i];
}
$approve[] = $arr['resim'];
$it = $approve;
$this->form_duzenle_model->cevapDuzenle($i,$arr['resim']);
}
}
redirect('form_duzenle/', 'refresh');
}else{
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik'=>$veri->baslik,
'veri' =>$veri,
'cevap' =>$veri2
);
$this->bc->addCrumb($veri->baslik,'form_duzenle/duzenle/'.$veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle',$data);
}
}
I'm trying to upload multiple images at once to my database. I was able to do it with single files but i'm not able to get it going with the html5 multiple option.
This is my form:
<form action="includes/saveImage.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" multiple="multiple" name="image[]" accept="image/*"> <input type="submit" value="upload">
</form>
and this is my saveImage.php
$files = array();
$fdata = $_FILES["image"];
if (is_array($fdata["name"]))
for ($i = 0; $i < count($fdata['name']); ++$i) {
$files[] = array(
'name' => $fdata['name'][$i],
'tmp_name' => $fdata['tmp_name'][$i],
'image' => file_get_contents($fdata['tmp_name'][$i]),
);
}
} else {
$files[] = $fdata;
}
foreach ($files as $file)
{
if (!$album_mysqli->query("INSERT INTO '1' VALUES ('','{$file['name']}','{$file['image']}',NOW())"))
{
print"error while uploading";
}
// print_r( $file );
}
If i uncomment the last print_r($file); it shows the binary data of the image file.
Any ideas why it won't upload to my database?
The database I want to write to uses a BLOB field for the image.
Solved my problem
There was some problem with the SQL-statement
Adding the pictures in this way works just fine...
foreach ($files as $file)
{
$image = file_get_contents($file['tmp_name']);
$result = $album_mysqli->prepare("INSERT INTO '1' VALUES ('', ?, ?, CURDATE())");
$result->bind_param("ss", $file['name'], $image);
if (!$result->execute())
{
echo"Problem on file {$file['name']}. <br/>";
}
else
{
echo("{$file['name']} was added to the database. <br/>");
}
$result->close();
}
You cant upload images to your database like this. You should eiter upload the image via PHP to a certain directory and insert into your database their filenames so that you can fetch them after that, or you can upload their base64 code into the database and put it in the image tag like this <img src="base64_code_of_the_image" />
foreach ($files as $file)
{
#move_uploaded_file($file['tmp_name'],<destinationfile>);
if (!$album_mysqli->query("INSERT INTO '1' VALUES
('','{$file['name']}','',NOW())"))
{
print"error while uploading";
}
print_r( $file );
}
You can't upload the images into the database directly as you are trying. If you want to do that you need to create BLOB object for that specific field in the database table.
Solved my problem
There was some problem with the SQL-statement
Adding the pictures in this way works just fine...
$files = array();
$fdata = $_FILES["image"];
if (is_array($fdata["name"]))
for ($i = 0; $i < count($fdata['name']); ++$i) {
$files[] = array(
'name' => $fdata['name'][$i],
'tmp_name' => $fdata['tmp_name'][$i],
'image' => file_get_contents($fdata['tmp_name'][$i]),
);
}
} else {
$files[] = $fdata;
}
foreach ($files as $file)
{
$image = file_get_contents($file['tmp_name']);
$result = $album_mysqli->prepare("INSERT INTO '1' VALUES ('', ?, ?, CURDATE())");
$result->bind_param("ss", $file['name'], $image);
if (!$result->execute())
{
echo"Problem on file {$file['name']}. <br/>";
}
else
{
echo("{$file['name']} was added to the database. <br/>");
}
$result->close();
}
<?php
//include connection here
include'connect.php';
if(isset($_POST['submit']))
{
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_size = $_FILES['image']['size'];
$data = $_FILES['image']['tmp_name'];
for($i=0; $i<=count($data)-1; $i++)
{
$name = addslashes($file_name[$i]);
$type = addslashes($file_type[$i]);
$size = addslashes($file_size[$i]);
$tmp = addslashes(file_get_contents($data[$i]));
$sql = "INSERT INTO t_home_pix(name, type, size, content) VALUES('".$name."','".$type."','".$size."','".$tmp."')";
mysqli_query($conn, $sql);
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
File:
<input type="file" multiple="multiple" name="image[]" accept="image/*">
<input type="submit" name="submit" value="upload">
</form>
This is my Controller
Image Controller:
class Admin_xxxxController extends Zend_Controller_Action
{
public function init()
{
$this->_helper->layout()->setLayout('admin');
if ($this->_helper->FlashMessenger->hasMessages()) {
$messages = $this->_helper->FlashMessenger->getMessages();
$this->view->messages = $messages[0];
}
}
public function preDispatch()
{
if(!Zend_Auth::getInstance()->hasIdentity()) {
if ('login' != $this->getRequest()->getActionName()) {
$this->_helper->redirector('index','login');
} else {
}
}
parent::preDispatch();
}
public function saveAction()
{
try {
if(isset($_POST['submit'])) {
$i=0;
$lmgdata=array();
foreach($_FILES as $k=>$v){
$post=$this->_request->getPost();
$path = "images/landimages";
$thumb="images/landimages/thumbnails";
if(!is_dir($path)){ // to check is folder exist or not
mkdir($path,'0777',true);
}
if(!is_dir($thumb)){ // to check is folder exist or not
mkdir($thumb,'0777',true);
}
$maxWidth="600"; $maxHeidht="500";$thumbwidth="100";$thumbheidht="75";
list($width,$height,$y) = getimagesize($v['tmp_name'][$i]);
$scale = min($maxWidth/$width, $maxHeidht/$height);
$scale1 = min($thumbwidth/$width, $thumbheidht/$height);
$s1=$v['name'][$i]; $destpath = $path.'/'.$s1; $thumbpath = $thumb.'/'.$s1;
if(move_uploaded_file($v['tmp_name'][$i],$destpath)){
//$this->resize($thumbpath, $destpath,$width, $height,$scale1,1);
$this->resize($destpath, $destpath,$width, $height,$scale,0 );
$lmgdata[$i]['lm_image']=$s1; // to save new image name in db
}else{
echo "not uploaded"; die();
}
$i++;
}
}
$post=$this->_request->getPost();
$data=array();
if($post['land_id'])
$data['land_id']=$post['land_id'];
$mapper= new Application_Model_xxxMapper();
$lmmapper= new Application_Model_yyyMapper();
if($lid = $mapper->save($data)){
$lmmapper->save($lmgdata, $lid);
$this->_helper->FlashMessenger(array('success'=>'xxx added Sucessfully'));
}else{
$this->_helper->FlashMessenger(array('failed'=>'xxx not added ,please try again'));
}
$this->_helper->redirector('index','xxxx','admin');
}
catch(Zend_Db_Exception $e)
{
echo $e->getMessage();
}
}
This is my add form where I upload multiple images
Add form:
<form action="<?php echo $this->url(array('controller'=>'lands','action'=>'save'),'admin',true);?>" method="post" enctype="multipart/form-data">
Upload Images:<input type="file" multiple name="land_image[]" id="land_image" class="form-control" autocomplete="off" title="">
I used for loop in controller to save multiple images and When I tried to upload multiple images and submit in add form. Only 1 image is getting save and that too only the thumnail is saved. How to get all the images saved
Your loop should look as follows:
foreach($_FILES['land_image']['tmp_name'] as $key => $tmp_name) {
$fileName = $_FILES['land_image']['name'][$key];
$fileSize = $_FILES['land_image']['size'][$key];
$fileTmp = $_FILES['land_image']['tmp_name'][$key];
$fileType = $_FILES['land_image']['type'][$key];
...
}
The answer is not relevant to the question asked. I will answer to my question:
public function saveAction($lmgdata)
{
try{
if(isset($_POST['submit']))
{ $i = 0;
foreach($_FILES as $k=>$v){
// to test is form submited or not
$post=$this->_request->getPost(); // get post result
$data=array(); // create an array to stroe posted details
$data['land_id']=$_SESSION['lid'];
//$data['lm_order']=$post['lm_order'];
/* below code for create a directory */
$path = "/propladder/public/images/landimages";
$thumb="/propladder/public/images/landimages/thumbnails";
if(!is_dir($path)){ // to check is folder exist or not
mkdir($path,'0755',true);
}
if(!is_dir($thumb)){ // to check is folder exist or not
mkdir($thumb,'0755',true);
}
/* below code for uploading in property image */
$maxWidth="600";
$maxHeidht="500";
list($width,$height,$y) = getimagesize($v['tmp_name'][$i]);
$scale = min($maxWidth/$width, $maxHeidht/$height);
$thumbwidth="100";
$thumbheidht="75";
$scale1 = min($thumbwidth/$width, $thumbheidht/$height);
$s1=$v['name'][$i];
$destpath = $path.'/'.$s1; // this is image fulll path
$thumbpath = $thumb.'/'.$s1; // this is image fulll path
if(move_uploaded_file($v['tmp_name'][$i],$destpath)){ // to upload image to destination
$this->resize($thumbpath, $destpath,$width, $height,$scale1,1);
$this->resize($destpath, $destpath,$width, $height,$scale,0 );
$data['lm_image']=$s1; // to save new image name in db
}else{
echo "not uploaded"; die();
}
$mapper=new Application_Model_xxxxMapper();
if($mapper->save($data)){
$this->_helper->FlashMessenger(array('success'=>'xxxx added sucessfully'));
}else{
$this->_helper->FlashMessenger(array('failed'=>'xxxx not added ,Try again'));
}
$i++;
}
} // end is post
//$this->_helper->redirector('index','xxxx','admin');
}catch(Zend_Db_Exception $e){
echo $e->getMessage();
}
}