Batch image upload in codeigniter - php

I am new to Codeigniter and i am trying to update multiple images using loop. But i am unable to do so because the foreach loop updates only 1 record if there are 3 records. Thanks in advance.
Controller.php
if(!empty($_FILES['product_image']['name'][0])) {
$number_of_files = sizeof($_FILES['product_image']['tmp_name']);
$files = $_FILES['product_image'];
$config = array(
'upload_path' => FCPATH.'uploads/product_images/',
'allowed_types' => 'jpg|png|jpeg'
);
for($i=0;$i<$number_of_files;$i++) {
$_FILES['product_image']['name'] = $files['name'][$i];
$_FILES['product_image']['type'] = $files['type'][$i];
$_FILES['product_image']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['product_image']['error'] = $files['error'][$i];
$_FILES['product_image']['size'] = $files['size'][$i];
$this->upload->initialize($config);
if($this->upload->do_upload('product_image')) {
$imgData = $this->upload->data();
}
$img[] = array(
'Image' => $files['name'][$i],
'SortOrder' => $_POST['sort_order'][$i]
);
//unlink("uploads/product_images/".$_POST['path']);
}
if($query = $this->M_Product->editProductImg($img,$prodId)) {
//$error = 0;
print_r($query);
} else {
//$error = 1;
}
}
Model.php
public function editProductImg($img,$prodId) {
$checkExist = $this->fetchSingleImage($prodId);
if(empty($checkExist)) {
if($this->db->insert_batch('tbl_product_images',$img)) {
return true;
} else {
return false;
}
} else {
foreach($img as $key => $value) {
$this->db->query("update tbl_product_images SET Image='".$value['Image']."',SortOrder='".$value['SortOrder']."' WHERE ProductId='".$prodId."'");
return $this->db->last_query();
}
}
}

Please check if number of files calculated are correct or try using
$number_of_files= count($_FILES);
Also change your first ' if ' to
if(!empty($_FILES))

Related

How to add multi images into database

I am trying to add multiple images one for the banner images other multiple images for the gallery images but when I try to add an image it gives me the error:
array to string conversation.
I want to add one image into the same table and other images into the different table so when I will show record into my view I can one banner image easily.
I will be very thankful if someone help me in this.
so here is the my view.
<div class="col-lg-12">
<label for="main image">Upload Main Image: </label><br>
<input type="file" name="image_file">
</div><br><br><br>
<div class="col-lg-12">
<label for="Image name">Upload Mutiple Images:</label><br>
<input type="file" required name="image_name[]" multiple/><br>
</div>
// Model
function addnews($data, $id ='')
{
$title = $this->input->post('title');
$address = $this->input->post('address');
$city = $this->input->post('city');
$zip = $this->input->post('zipcode');
$type = $this->input->post('propertytype');
$status = $this->input->post('status');
$price = $this->input->post('price');
$description = $this->input->post('Description');
$userfile = $this->input->post('[image_file]');
$bedrooms = $this->input->post('bedrooms');
$rooms = $this->input->post('rooms');
$bath = $this->input->post('bathroom');
$garages = $this->input->post('gerages');
$date = $this->input->post('date');
$amenities = implode(',',$this->input->post('check'));
$w = array (
'title' => $title,
'address' => $address,
'city' => $city,
'zip' => $zip,
'type' => $type,
'status' => $status,
'description' => $description,
'bedrooms' => $bedrooms,
'rooms' => $rooms,
'price' => $price,
'userfile' => $data,
'bath' => $bath,
'date' => $date,
'garages' => $garages,
'amenities' => $amenities
);
$this->db->insert_batch("property", $w);
$id = $this->db->insert_id();
foreach ($data as $row) { // here data is from parameter
$data1[] = array(
'property_id' => $id, //Insert Inserted id
'image_name' => $row['file_name'] // this line is changed
);
}
}
// My controller.
public function addlisting()
{
$this->load->library('upload');
$config['upload_path']='./uploads';
$config['allowed_types']='*';
$this->upload->initialize($config);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image_file')) {
$this->session->set_flashdata('msg',"Failed To Apply. Please Check All The Fields.");
redirect(site_url('Welcome/add_listing'));
} else {
$fd = $this->upload->data();
$fn = $fd['file_name'];
//$this->User_model->addnews($fn);
$image = array();
$ImageCount = count($_FILES['image_name']['name']);
for ($i = 0; $i < $ImageCount; $i++) {
$_FILES['file']['name'] = $_FILES['image_name']['name'][$i];
$_FILES['file']['type'] = $_FILES['image_name']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['image_name']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['image_name']['error'][$i];
$_FILES['file']['size'] = $_FILES['image_name']['size'][$i];
// File upload configuration
$uploadPath = './uploads';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
// Upload file to server
if ($this->upload->do_upload('file')) {
// Uploaded file data
$imageData = $this->upload->data();
$uploadImgData[$i]['file_name'] = $imageData['file_name'];
} else {
$this->session->set_flashdata('msg',"Error while uploading Data");
// $this->User_model->addnews($uploadImgData);
redirect(site_url('Welcome/add_listing'));
}
}
if (!empty($uploadImgData)) {
//Insert files data into the database
$this->User_model->addnews($uploadImgData);
$this->User_model->addnews($fn);
// $query = implode(",",$uploadImgData);
// $insert = $this->User_model->add($uploadImgData);
$this->session->set_flashdata('msg',"Property Uploaded successfully");
redirect('Welcome/add_listing');
}
}
try to change name or config array
public function add_model()
{
$this->before_login();
$data = array();
$data['mode'] = "ADD";
$db_name = 'para';
$table = 'models';
$sess = $this->session->userdata('admin');
$data['a_name'] = $sess['name'];
$data['record'] = $this->Paramodel->select('brand','brand_name,id');
if($this->input->post('submit'))
{
$this->Database->add_new_model($table,$db_name);
foreach($_POST as $key=>$value)
{
$$key=trim($value);
}
// Form Validation Run
if($this->form_validation->run('add_model'))
{
if(strlen($_FILES['model_display_picture']['name']) > 0)
{
$config['upload_path'] = './assets/Model/';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = 2048;
$config['encrypt_name'] = TRUE;
// directry Path
$this->load->library('upload',$config);
$slug = $this->clean_url($model_name);
$this->upload->initialize($config);
if($this->upload->do_upload('model_display_picture'))
{
$result=$this->last_record('models')[0]['setord'];
// echo "<pre>";
// print_r($result);
// exit;
if($result == "" ){ $last_setord_no = 1; }else{ $last_setord_no = $result+1; }
$image_path = './assets/Model/'.$this->upload->data('file_name');
// INSERT DATA
$ins['brand_id'] = $brand_id;
$ins['model_type'] = $model_type;
$ins['model_name'] = $model_name;
$ins['model_description'] = $model_description;
$ins['model_display_image'] = $image_path;
$ins['status'] = $status;
$ins['slug'] = $slug;
$ins['setord'] = $last_setord_no;
$ins['meta_title'] = addslashes($meta_title);
$ins['meta_descryption'] = $meta_description;
$ins['meta_keywords'] = $meta_keywords;
$ins['u_create_date'] = date('Y-m-d H:i:s');
// INSERT QUERY
$insert = $this->Paramodel->insert('models',$ins);
$insert_id = $this->db->insert_id();
$this->_create_thumbs($this->upload->data('file_name'));
// INSERT SUCCESS CONDITION
if( $insert == 1 )
{
$count = count($_FILES['model_images']['name']);
if( $count > 0)
{
$this->Database->model_image('model_image');
for($i = 0 ; $i < $count ; $i++ )
{
$_FILES['single']['name'] = $_FILES['model_images']['name'][$i];
$_FILES['single']['type'] = $_FILES['model_images']['type'][$i];
$_FILES['single']['tmp_name'] = $_FILES['model_images']['tmp_name'][$i];
$_FILES['single']['size'] = $_FILES['model_images']['size'][$i];
$_FILES['single']['error'] = $_FILES['model_images']['error'][$i];
$config1['upload_path'] ='./assets/Model/';
$config1['allowed_types'] = 'jpg|jpeg|png';
$config1['max_size'] = 2048;
$config1['encrypt_name'] = TRUE;
// echo "<pre>";
// print_r($config1);
$this->load->library('upload',$config1);
$this->upload->initialize($config1);
// echo "<pre>";
// print_r($_FILES['single']);
// echo "------------------";
if($this->upload->do_upload('single'))
{
// echo "<pre>";
// print_r($config1);
$images_path = './assets/Model/'.$this->upload->data('file_name');
$ins_up['model_id'] = $insert_id;
$ins_up['model_image'] = $images_path;
$result = $this->Paramodel->insert('model_image',$ins_up);
$this->_create_thumbs($this->upload->data('file_name'));
if($result == 1)
{
$this->session->set_flashdata('insert','Model Insert SuccessFully.');
redirect('manage-models');
}
}
else
{
$data['error'][$i] = array('error' => $this->upload->display_errors());
}
}
}
}
}
else
{
$data['error'][$i] = array('error' => $this->upload->display_errors());
}
}
}
}
$this->load->view('admin/add_model',$data);
}
my code is this try it.

REST API generation for Opencart

I tried to generate a REST API for my customers, categories, products, coupons, manufacturers and all others to use it in my Android application, but I can't get any solution.
Can anyone tell me how to create APIs in opencart 3.0.2.0?
Make a custom controller in catalog > Controller > api folder
Create controller file name: allproducts.php
You can copy following code and paste of allproducts.php
<?php
class ControllerApiAllproducts extends Controller {
private $error = array();
// All Products
public function index(){
$products = array();
$this->load->language('catalog/product');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$error[]['no_json']= "No JSON";
$product_total = $this->model_catalog_product->getTotalProducts();
$results = $this->model_catalog_product->getProducts();
foreach ($results as $result) {
if (is_file(DIR_IMAGE . $result['image'])) {
$image = $this->model_tool_image->resize($result['image'], 40, 40);
} else {
$image = $this->model_tool_image->resize('no_image.png', 40, 40);
}
$special = false;
$product_specials = $this->model_catalog_product->getProductSpecials($result['product_id']);
foreach ($product_specials as $product_special) {
//if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
$special = $product_special['price'];
//break;
// }
}
$shop_products['shop_products'][] = array(
'product_id' => $result['product_id'],
'image' => $image,
'name' => $result['name'],
'model' => $result['model'],
'price' => $result['price'],
'special' => $special,
'quantity' => $result['quantity'],
'status' => $result['status']
);
}
if (isset($this->request->get['json'])) {
echo json_encode($shop_products);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// Product info Page
public function productInfo(){
$this->load->language('catalog/product');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$product_details = array();
$error['fail'] = 'Failed';
if (isset($this->request->get['product_id'])) {
//$product_details['product_id'] = $this->request->get['product_id'];
$product_details = $this->model_catalog_product->getProduct($this->request->get['product_id']);
echo json_encode($product_details);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// Category Listing Page
public function categories(){
$shop_categories = array();
$this->load->model('catalog/category');
$error['fail'] = 'Failed';
if (isset($this->request->get['json'])) {
$shop_categories =$this->model_catalog_category->getCategories();
echo json_encode($shop_categories);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// Product Listing By Category
public function categoryList(){
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$error['fail'] = 'Failed';
if (isset($this->request->get['path'])) {
$url = '';
$path = '';
$parts = explode('_', (string)$this->request->get['path']);
$category_id = (int)array_pop($parts);
foreach ($parts as $path_id) {
if (!$path) {
$path = (int)$path_id;
} else {
$path .= '_' . (int)$path_id;
}
$category_info = $this->model_catalog_category->getCategory($path_id);
}
} else {
$category_id = 0;
}
$category_info = $this->model_catalog_category->getCategory($category_id);
if ($category_info) {
$url = '';
//$data['categories'] = array();
$results = $this->model_catalog_category->getCategories($category_id);
foreach ($results as $result) {
$filter_data = array(
'filter_category_id' => $result['category_id'],
'filter_sub_category' => true
);
}
$products = array();
$filter_data = array(
'filter_category_id' => $category_id
);
$product_total = $this->model_catalog_product->getTotalProducts($filter_data);
$products = $this->model_catalog_product->getProducts($filter_data);
echo json_encode($products); die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// All Manufacturers Listing
public function manufactureList() {
$this->load->model('catalog/manufacturer');
$this->load->model('tool/image');
$error['fail'] = 'Failed';
$manufactureList = array();
if (isset($this->request->get['json'])) {
$manufactureList = $this->model_catalog_manufacturer->getManufacturers();
echo json_encode($manufactureList);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// Manufactur info Page
public function manufactureInfo() {
$this->load->model('catalog/manufacturer');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$error['fail'] = 'Failed';
if (isset($this->request->get['manufacturer_id'])) {
$manufactureInfo = $this->model_catalog_manufacturer->getManufacturer($manufacturer_id);
echo json_encode($product_details);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// Category Listing Page
public function specialProduct(){
$specialProduct = array();
$this->load->model('catalog/product');
$this->load->model('tool/image');
$error['fail'] = 'Failed';
if (isset($this->request->get['json'])) {
$specialProduct = $this->model_catalog_product->getProductSpecials();
echo json_encode($specialProduct);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
}
I made following APIs and its path (see Postman apps):
ALL Products : http://examples.com/index.php?route=api/allproducts&json
Product By ID : http://examples.com/index.php?route=api/allproducts/productInfo&json&product_id=30
ALL Categories : http://examples.com/index.php?route=api/allproducts/categories&json
Category Wise Product : http://examples.com/index.php?route=api/allproducts/categoryList&json&path=25_28
ALL Manufacturers : http://examples.com/index.php?route=api/allproducts/manufactureList&json
Manufactur By ID : http://examples.com/index.php?route=api/allproducts/manufactureInfo&manufacturer_id=11
Special Products : http://examples.com/index.php?route=api/allproducts/specialProduct&json

Script not Iterating through all files in directory

PHP Script written for SuiteCRM improting is supposed to loop through all files in the directory and import each to Database. Having a lot of trouble.
Script reads and works on the first file only then finishes when it should loop :(
Importing works fine and data is added the the database from first file.
function MemberImportJob()
{
try
{
$config = new Configurator();
$config->loadConfig();
$xmlDataDir = 'custom/wimporter/eidimport';
$directoryContent = scandir($xmlDataDir);
//foreach ($directoryContent as $itemFile)
foreach (glob($xmlDataDir) as $itemfile)
{
var_dump($itemfile);
if (is_dir($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile)) continue;
if (strcasecmp(substr($itemFile, -4), ".csv") != 0) continue;
$oFile = fopen($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile, 'r');
if ($oFile !== FALSE)
{
$header = NULL;
$data = Array();
while (($data[] = fgetcsv($oFile, 90000, ',')) !== FALSE) { }
fclose($oFile);
//combine into a nice associative array:
$arow=Array();
$fields = array_shift($data);
foreach ($data as $i=>$arow)
{
array_combine " . $i);
if (is_array($arow)) {
$data[$i] = array_combine($fields, $arow);}
}
unset($arow);
$num = count($data);
for ($row=0; $row < $num - 1; $row++)
{
$Member = BeanFactory::getBean("locte_Membership");
$Member=$Member->retrieve_by_string_fields(array('last_name' => $data[$row]["LAST NAME"], 'first_name' => $data[$row]["FIRST NAME"], 'lcl_affiliate_number' => $data[$row]["AFFILIATE"]));
$MemberID = $Member->id;
if (is_null($Member)) {
$Member = BeanFactory::newBean('locte_Membership');
$delta = fillPerson($data[$row], $Member, "FULL NAME");
if(count($delta))
{
$Member_id = $Member->save();
}
} else {
v
var_dump($Member->id);
$delta = fillFoundrecord($data[$row], $Member, "FULL NAME");
echo("record Updated!");
$Member_id = $Member->save();
}
unset($data[$row]);
}
}
return true;
}
} catch (Exception $e)
{
return false;
}
}

cannot upload the file through admin panel

Column count doesn't match value count at row 1
public function file_upload($file,$dir)
{
$uploads_dir = $dir;
$original_file = addslashes($file['name']); // storing file name
$buffer_path = $file['tmp_name']; // storing temp buffer path
$unique_name = time().$original_file; // creating unique file name by appending time stamp
$path = $uploads_dir.$unique_name;
// uploading file using default function
if(move_uploaded_file($buffer_path,$path))
{
return $path;
}
else
{
return "No";
}
}
function multiple_image_upload($file,$path)
{
//echo "<pre>";print_r($file);
if(empty($file['name'][0]))
{
return "No file selected";
}
else
{
$cnt = 0 ;
foreach($file['name'] as $filename)
{
$buffer_path = $file['tmp_name'][$cnt];
$unique_file_name = $path.date('Y-m-d H-i-s').time().$filename;
move_uploaded_file($buffer_path,$unique_file_name);
$final_file_path[] = $unique_file_name;
$cnt++;
}
return $final_file_path;
}
}
function multiple_thumb($msg,$filedata,$thumb_folder)
{
if(!is_dir($thumb_folder))
{
mkdir($thumb_folder,0755);
}
$cnt=0;
foreach($msg as $val)
{
/* echo $val;
echo "<br />"; */
//echo "<pre>";
//print_r($filedata['name']);
$o_image = imagecreatefromjpeg($val);
$o_width = imageSX($o_image);
$o_height = imageSY($o_image);
$n_width = 230;
$n_height = 250;
$new_image = imagecreatetruecolor($n_width,$n_height);
//print_r($new_image);
imagecopyresampled($new_image,$o_image,0,0,0,0,$n_width,$n_height,$o_width,$o_height);
$thumb_unique_path = $thumb_folder.date('Y-m-d H-i-s').time().$filedata['name'][$cnt];
imagejpeg($new_image,$thumb_unique_path);
$thumb_final_data[] = $thumb_unique_path;
$cnt++;
}
//print_r($thumb_final_data);
return $thumb_final_data;
}

Creating thumbnail images while uploading multiple images with php

I'm using PHP/MySQL to upload multiple images for photo album. The information associated with the images (filenames, extensions, descriptions etc.) is stored in database as base64 encoded data. I'm also able to edit the album images. My problem now is that I also want to create thumbnails for each of the images when uploading them on insert and edit mode and also store the information for the thumbnails the same way I do for the images (base64 encoded). What's the best way to do that? Thanks
Here's my code:
<?php
//Code for the editing albums in database
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
//select photo album and get photos and descriptions to be merged with new.
$album_id = $_REQUEST['album_id'];
$old_photos = null;
$old_descriptions = null;
$getAlbumQ = mysql_query("select * from albums where id='$album_id'");
while ($old_album = mysql_fetch_array($getAlbumQ)) {
$old_photos = unserialize(base64_decode($old_album['photos']));
$old_descriptions = unserialize(base64_decode($old_album['descriptions']));
$old_timestamp=$old_album['timestamp'];
}
if (isset($_POST['album_name']) && isset($_POST['desc'])) {
$name = mysql_real_escape_string($_POST['album_name']);
$desc = mysql_real_escape_string($_POST['desc']);
$idesc = array();
$target_path = "/uploads/albums/";
foreach ($_FILES as $key => $value) {
foreach ($value as $k => $v) {
if ($k === 'name' && $v !== '') {
break;
} else {
unset($_FILES[$key]);
}
}
//first upload photos
$path = $target_path . basename($old_timestamp.$value['name']);
if(move_uploaded_file($value['tmp_name'], $path)) {
$hasUpload = true;
}
}
for ($j = 1; $j < 21; $j++) {
$img_index = $j;
$img_desc = $_POST['desc_' . $img_index];
array_push($idesc, $img_desc);
}
foreach ($_FILES as $key => $value) {
foreach ($value as $k => $v) {
if ($k=='name' && $v!='') {
break;
} else {
unset($_FILES[$key]);
}
}
}
function merge(&$a, &$b){
$keys = array_keys($a);
foreach($keys as $key){
if(isset($b[$key])){
if(is_array($a[$key]) and is_array($b[$key])){
merge($a[$key],$b[$key]);
}
else{
$a[$key] = $b[$key];
}
}
}
$keys = array_keys($b);
foreach($keys as $key){
if(!isset($a[$key])){
$a[$key] = $b[$key];
}
}
}
for ($i = 1; $i < 21; $i++) {
$file_index = $i;
$file_number = $_POST['image_' . $file_index];
if($_FILES['image_'.$i]['name']!= ''){
$hasUpload = true;
$presults = merge($old_photos, $_FILES);
$dresults = array_merge($old_descriptions, $idesc);
$images = base64_encode(serialize($presults));
$descriptions = base64_encode(serialize($dresults));
$posted = date("Y-m-d H:i:s");
}
else {
$hasUpload = false;
$presults = $old_photos;
$dresults = $idesc;
$images = base64_encode(serialize($presults));
$descriptions = base64_encode(serialize($dresults));
$posted = date("Y-m-d H:i:s");
}
}
}
if (mysql_query("update albums set description = '$desc', name = '$name', photos='$images', descriptions='$descriptions' where id='$album_id'")) {
$hasAlbums = true;
} else {
$hasErrors = true;
}
} else {
//Code for the inserting albums in database
if (isset($_POST['album_name'])) {
if (isset($_POST['album_name']) && isset($_POST['desc'])) {
$name = mysql_real_escape_string($_POST['album_name']);
$desc = mysql_real_escape_string($_POST['desc']);
$idesc = array();
$timestamp = time();
$target_path = "/uploads/albums/";
foreach ($_FILES as $k => $v) {
//first upload photos
$path = $target_path . basename($timestamp.$v['name']);
if(move_uploaded_file($v['tmp_name'], $path)) {
$img_index = explode('_', $k);
$img_index = $img_index[1];
$img_desc = $_POST['desc_' . $img_index];
array_push($idesc, $img_desc);
$file_name = $timestamp.$v['name'];
$hasUpload = true;
}
}
$images = base64_encode(serialize($_FILES));
$descriptions = base64_encode(serialize($idesc));
$posted = date("Y-m-d H:i:s");
$query = mysql_query("
INSERT INTO albums (description, posted, photos, name, descriptions, timestamp)
VALUES ('$desc', '$posted', '$images', '$name', '$descriptions', '$timestamp')
");
}
}
}
?>
I tried a simple thumbnail script found on this tutorial and it worked perfectly: http://net.tutsplus.com/articles/news/how-to-dynamically-create-thumbnails/
Thanks for your suggestions
You can use the Thumbnail class from
http://freecode.com/projects/easyphpthumbnailclass
You may use ImageMagick's resizeImage method.
explained in a tutorial here http://coffeeshopped.com/2009/01/creating-image-thumbnails-using-php-and-imagemagick
Also, you may try phpThumb() function and is available at sourceforge here http://phpthumb.sourceforge.net/
Hope this helps..

Categories