insert multidimensional array into mysqli db - image

I'm really hoping someone can help me out before I throw myself off a cliff. I have created a class to upload multiple images stored in a multidimensional array. The images are moved to a selected folder. I want to store the details of each image in a mysqli database. Each image should share a unique key which identifies it to a specific product.
The itm_pic_details (images) table has 5 fields
id auto increment id
itm_pic_id unique id linked to the product
itm_pic_dsc name of file
itm_file_date date added
itm_file_user (not needed to be filled in at this stage. Only for transaction purposes)
itm_file_path (location of image)
I have included the 2 most important functions in my Upload class
protected function processFile($filename,$error,$size, $type,$tmp_name,$overwrite){
$OK = $this->checkError($filename,$error);
if ($OK) {
$sizeOK = $this->checkSize($filename, $size);
$typeOK = $this->checkType($filename, $type);
if ($sizeOK && $typeOK) {
$name = $this->checkName($filename, $overwrite);
$success = move_uploaded_file($tmp_name, $this->_destination . $name);
if ($success) {
$message = "$filename uploaded successfully";
if ($this->_renamed) {
$message .= " and renamed $name";
}
$this->_messages[] = $message;
} else {
$this->_messages[] = 'Could not upload ' . $filename;
}
}
}
}
public function move($overwrite = false) {
$field = current($this->_uploaded);
if(is_array($field['name'])){
foreach($field['name'] as $number => $filename){
//process the multiple upload
$this->_renamed = false;
$this->processFile($filename,$field['error'][$number],$field['size'] [$number],$field['type'][$number],$field['tmp_name'][$number], $overwrite);
}
} else {
$this->processFile($field['name'],$field['error'],$field['size'],$field['type'],$field['tmp_name'],$overwrite);
}
}

Related

here my code and i want to save image url in database i am using laravel my question is how i save image url in database

here my code and i want to save image url in database i am using laravel my question is how i save image url in database
public function save(Request $req)
{
if(request()->hasFile('photo')){
$path = base_path() . '/public/user-uploads/employee-docs/';
$repath = '/public/user-uploads/employee-docs/'.request('project');
if (!file_exists($path))
{
mkdir($path);
}
$path = $path.'/'.request('project');
if (!file_exists($path))
{
mkdir($path);
}
$name = Carbon::now()->format('Y-m-d-H-i-s_u');
$file1 = request()->file('photo');
if($file1->isValid()) {
$file1->move($path, $name.'.'.$file1->getClientOriginalExtension());
$file1_url = $repath.'/'.$name.'.'.$file1->getClientOriginalExtension();
$photo = new attendance;
$photo ->user_id=$req->user_id;
$photo ->image_url=$req->image_url;
return ['status'=>1, 'data'=>$file1_url];
} else{
return ['status'=>0, 'data'=>'Invalid image'];
}
} else{
return ['status'=>0, 'data'=>'There is no image'];
}
}
Looks like you have not saved the object $photo
$photo = new attendance;
$photo->user_id=$req->user_id;
$photo->image_url=$req->image_url;
$photo->save() // add this line

ErrorException in AssetController.php line 21: Trying to get property of non-object

I have this code source that i'm trying to use in one of my projects, it worked with laravel 5.2. This the function in the assetController:
namespace App\Http\Controllers;
use App\Setting;
use File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AssetController extends Controller
{
/**
* List all image from image directory
*/
public function getAsset()
{
//Get Admin Images
$adminImages = array();
//get image file array
$images_dir = Setting::where('name', 'images_dir')->first();
$folderContentAdmin = File::files($images_dir->value);
//check the allowed file extension and make the allowed file array
$allowedExt = Setting::where('name', 'images_allowedExtensions')->first();
$temp = explode('|', $allowedExt->value);
foreach ($folderContentAdmin as $key => $item)
{
if( ! is_array($item))
{
//check the file extension
$ext = pathinfo($item, PATHINFO_EXTENSION);
//prep allowed extensions array
if (in_array($ext, $temp))
{
array_push($adminImages, $item);
}
}
}
//Get User Images
$userImages = array();
$userID = Auth::user()->id;
$images_uploadDir = Setting::where('name', 'images_uploadDir')->first();
if (is_dir( $images_uploadDir->value . "/" .$userID ))
{
$folderContentUser = File::files($images_uploadDir->value . "/" .$userID );
if ($folderContentUser)
{
foreach ($folderContentUser as $key => $item)
{
if ( ! is_array($item))
{
//check the file extension
$ext = pathinfo($item, PATHINFO_EXTENSION);
//prep allowed extensions array
//$temp = explode("|", $this->config->item('images_allowedExtensions'));
if (in_array($ext, $temp))
{
array_push($userImages, $item);
}
}
}
}
}
//var_dump($folderContent);
//var_dump($adminImages);
return view('assets/images', compact('adminImages', 'userImages'));
}
The problem is in the line 21 :
//get image file array
$images_dir = Setting::where('name', 'images_dir')->first();
$folderContentAdmin = File::files($images_dir->value);
From my research I find out that the reason is because the setting table is empty which it is true.
Please tell me if there is another cause to that problem if it's not the case I need a solution because I don't have a way to fill that table except doing it from the database itself (phpmyAdmin)

How can I encrypt a Joomla Configuration Parameter that is stored in the database?

I found this question, which is identical to what I need to do:
How do you Encrypt and Decrypt a PHP String?
I've got everything working to the point of encrypting the data before it is saved. In the event function onExtensionBeforeSave, I have access to the table. I can get the values that need to be encrypted from jinput and encrypt them. What I can't figure out is how to put the encrypted data into the table object in a way that it will replace the un-encrypted data before it is stored/saved.
I was able to figure this out. In the extension event onExtensionBeforeSave, I get the post data, load the config.xml file to check the form fields for my custom fields (type='encryptedtext'), encryt those and use the table object to bind and check it, so it will be stored correctly.
function onExtensionBeforeSave($context, $table, $isNew)
{
$jinput = JFactory::getApplication()->input;
$component = $jinput->get('component');
if($component !== 'com_store') // Only encrypting fields in the store component for now
{
return true;
}
$form_path = JPATH_ADMINISTRATOR . '\\components\\' . $component . '\\config.xml';
$xml = simplexml_load_file($form_path);
$has_encrypted = false;
foreach($xml->fieldset as $fieldset)
{
foreach($fieldset as $field)
{
if($field['type'] == 'encryptedtext') // is our custom form field type to be encrypted
{
$has_encrypted = true;
if(!$fields) // get fields if it hasn't already been done
{
$fields = $jinput->get('jform', '', 'array');
}
$field = (string)$field['name'];
$value = (string)$fields[$field];
$cipher = "aes-256-ctr";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen, $isStrongCrypto);
if (!$isStrongCrypto)
{
throw new \Exception("Not a strong key");
}
$keyhash = openssl_digest($component, 'sha256', true);
$opts = OPENSSL_RAW_DATA;
$encrypted = openssl_encrypt($value, $cipher, $keyhash, $opts, $iv);
if ($encrypted === false)
{
throw new \Exception('Encryption failed: ' . openssl_error_string());
}
$result = $iv . $encrypted;
$result = base64_encode($result);
$fields[$field] = $result;
}
}
}
if(!has_encrypted)
{
return false;
}
$data = array(
'params'=>$fields,
'option'=>$component
);
if (!$table->bind($data))
{
throw new RuntimeException($table->getError());
}
if (!$table->check())
{
throw new RuntimeException($table->getError());
}
return true;
}
All that is left is to decrypt it in the getInput function of the custom field. I answer this in case someone needs it, and I would love some critique if people see improvements, or if it's complete junk ...

Saving multiple images for one product using one to many in codeigniter

I am new in code igniter.
Here is what I am trying to do. I have lists of products stored in database table name products. For each products i need to insert multiple images. I have created two tables, products and productimage. I have made the product_id of table productimage the foreign key, referencing the product_id of table products. Now i want to save the datas from form. Here is what i did previously Saving images in a single row by imploding
But it became quite difficult for me to manage CRUD(like editing and deleting pictures).
So i am trying to do the above mentioned way. I am not finding the way to start. Can anyone please instruct me, how can I start?
Okay now I have done some coding here. This is my controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->model('product_model');
$this->load->helper(array('form','url'));
//Codeigniter : Write Less Do More
}
public function index()
{
$data['products']=$this->product_model->get_product();
$this->load->view('/landing_page',$data);
}
public function create()
{
#code
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('product_name','Product_Name','required');
if($this->form_validation->run()=== FALSE)
{
$this->load->view('products/create');
}
else {
$this->product_model->set_product();
$data['products']=$this->product_model->get_product();
redirect('/');
}
}
}
This is my model:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product_model extends CI_Model{
public function __construct()
{
$this->load->database();
parent::__construct();
//Codeigniter : Write Less Do More
}
public function get_product()
{
#code
$query=$this->db->get('products');
return $query->result_array();
}
public function set_product($id=0)
{
#code
// if($this->input->post('userSubmit')){
$picture=array();
$count=count($_FILES['picture']['name']);
//Check whether user upload picture
if(!empty($_FILES['picture']['name'])){
foreach($_FILES as $value)
{
for($s=0; $s<=$count-1; $s++)
{
$_FILES['picture']['name']=$value['name'][$s];
$_FILES['picture']['type'] = $value['type'][$s];
$_FILES['picture']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['picture']['error'] = $value['error'][$s];
$_FILES['picture']['size'] = $value['size'][$s];
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture[] = $uploadData['file_name'];
}
else{
$picture = '';
}
}
}
}//end of first if
else{
$picture = '';
}
$data=array(
'product_name'=>$this->input->post('product_name')
);
$picture=array(
'product_id'=>$this->db->get('products',$id),
'picture_image'=>$picture
);
if ($id==0)
{
return $this->db->insert('products',$data);
return $this->db->insert('images',$picture);
}
else {
$this->db->where('id',$id);
return $this->db->update('products',$data);
return $this->db->update('images',$picture);
}
}
}
Noe the case is when my form opens i am being able to fill product name and upload image files. When i submit it doesn't throws any errors too. But only product name is stored in products table and nothing happens to images table. No any images are inserted. Neither any error is thrown by browser. Simply images
table is empty. What's the problem here?
Let me help you with the Controller .. You need to check for all the uploaded files. They are $_FILES. Loop through the array, upload them on the server and than call a model function to add them in your product Images table
If CI Upload is too tricky for you. Use the following Controller function
public function upload_images()
{
// following IF statement only checks if the user is logged in or not
if($this->session->userdata['id'] && $this->session->userdata['type']=='user')
{
if($_FILES)
{
// check whether there are files uploaded / posted
if(isset($_FILES['files'])){
$data['errors']= array();
$extensions = array("jpeg","jpg","png");
//Loop through the uploaded files
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$i=1;
if($file_size > 2097152){
$data['errors'][$i]='File '.$i.' size must be less than 2 MB';
$i++;
}
// Set upload destination directory
$desired_dir="uploads";
if(empty($data['errors'])==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
// Upload the file.
move_uploaded_file($file_tmp,"uploads/".$file_name);
// Call a function from model to save the name of the image in images table along with entity id
$this->post_model->addImage('property_images',$file_name,$this->uri->segment(3));
}else{ //rename the file if another one exist
$new_dir="uploads/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
}else{
$data['contact']=$this->admin_model->getContactDetails();
$data['images']=$this->post_model->getPropertyImages($this->uri->segment(3));
//load views
}
}
if(empty($data['errors']))
{
redirect(base_url().'dashboard');
}
else
{
$data['contact']=$this->admin_model->getContactDetails();
$data['images']=$this->post_model->getPropertyImages($this->uri->segment(3));
//load views
}
}
}
else
{
//Load view
}
}
else
{
redirect(base_url().'user/login');
}
}
Incase anyone is having the same problem then here is the solution. Just do this in your upload function.(code by my friend Amani Ben azzouz)
public function set_product($id=0){
$picture=array();
$count=count($_FILES['picture']['name']);
//Check whether user upload picture
if(!empty($_FILES['picture']['name'])){
foreach($_FILES as $value){
for($s=0; $s<=$count-1; $s++){
$_FILES['picture']['name']=$value['name'][$s];
$_FILES['picture']['type'] = $value['type'][$s];
$_FILES['picture']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['picture']['error'] = $value['error'][$s];
$_FILES['picture']['size'] = $value['size'][$s];
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture[] = $uploadData['file_name'];
}
}
}
}//end of first if
$data=array('product_name'=>$this->input->post('product_name'));
if ($id==0){
$this->db->insert('products',$data);
$last_id = $this->db->insert_id();
if(!empty($picture)){
foreach($picture as $p_index=>$p_value) {
$this->db->insert('images', array('product_id'=>$last_id,'images'=>$p_value));
}
}
}
else {
$this->db->where('id',$id);
$this->db->update('products',$data);
if(!empty($picture)){
foreach($picture as $p_index=>$p_value) {
$this->db->update('images', array('product_id'=>$last_id,'images'=>$p_value) ); // --> this one?
}
}
}
}
This is for inserting and updating too. If you simply want do insert just delete the parameter passed as 'id' and cut that if and else part write a plain code of inside 'if'.
function contract_upload(){ // function to call from your view.
$data = array();
// If file upload form submitted
if(!empty($_FILES['files']['name']) AND !empty('user_id')){
$filesCount = count($_FILES['files']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
// File upload configuration
$uploadPath = './uploads/contract/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['encrypt_name'] = TRUE;
// 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
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['emp_id'] = $this->input->post('user_id');
}
}
if(!empty($uploadData)){
// Insert files data into the database
$insert = $this->Contract_model->insert($uploadData);
// Upload status message
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('messageactive', $statusMsg);
}
}
redirect('contract'); // redirect link, where do you want to redirect after successful uploading of the file.
}
// Model Function
public function insert($data = array()){
$insert = $this->db->insert_batch('employee_contract_files', $data); // table name and the data you want to insert into database.
return $insert?true:false;
}
Remember one thing, you should write your HTML as below:
<input type="file" name="files[]" multiple />

Joomla 2.5 method save()

Is there a way to show the changed values after saving within the Joomla save method?
For example, when I edit a "maxuser" field and save it, I´d like to show the old and the new value.
I tried this by comparing "getVar" and "$post", but both values are the same.
function save()
{
...
$maxuser1 = JRequest::getVar('maxuser');
$maxuser2 = $post['maxuser'];
...
if($maxuser1 != $maxuser2) {
$msg = "Not the same ...";
}
...
}
It's better to override JTable, not the Model. Heres sample code:
public function store($updateNulls = false) {
$oldTable = JTable::getInstance(TABLE_NAME, INSTANCE_NAME);
$messages = array();
if ($oldTable->load($this->id)) {
// Now you can compare any values where $oldTable->param is old, and $this->param is new
// For example
if ($oldTable->title != $this->title) {
$messages[] = "Title has changed";
}
}
$result = parent::store($updateNulls);
if ((count($messages) > 0) && ($result === true)){
$message = implode("\n", $messages);
return $message;
} else {
return $result;
}
}
This will return message string if there are any, true if there are no messages and save succeeded and false if saving failed. So all you have to do is check returned value in model and set right redirect message.
In the controller you can use the postSaveHook which gives you access to the validated values.

Resources