Screen Shot of HTML Form.
Can you suggest me where am I doing mistakes in my Laravel app, each time i am uploading multiple files throug the form, files is uploading perfectly in given location, but only 1 records are being inserted into database table. Here is my code...
// Upload bg_certificateArr photo
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
initialize $ac_bg for every foreach loop.
if ($request->hasFile('bg_certificate')) {
foreach ($request->file('bg_certificate') as $key => $file) {
$ac_bg = new AccountBankGuarantee; // like this
// Get image extention
$extention = $file->getClientOriginalExtension();
// Generate new image name
$bgCertImgName = 'ac-bg-cert-' . date('Y-m-d-H-i-s') . '.' . $extention;
$bgCertImgPath = 'accountant/images/bank_guarantee/' . $bgCertImgName;
// Upload Profile Image
Image::make($file)->save($bgCertImgPath);
// Insert data into bank guarantee table
$bg_amountArr = $data['bg_amount'];
$bg_numberArr = $data['bg_number'];
$bank_idArr = $data['bank_id'];
$bg_from_dateArr = $data['bg_from_date'];
$bg_to_dateArr = $data['bg_to_date'];
$bg_amount = $bg_amountArr[$key];
$bg_number = $bg_numberArr[$key];
$bank_id = $bank_idArr[$key];
$bg_from_date = $bg_from_dateArr[$key];
$bg_to_date = $bg_to_dateArr[$key];
// echo '<pre>';
// print_r($bg_to_date);
// die();
$ac_bg->school_id = $schoolID;
$ac_bg->ledgers_id = $acLedger->id;
$ac_bg->bg_amount = $bg_amount;
$ac_bg->bg_number = $bg_number;
$ac_bg->bank_id = $bank_id;
$ac_bg->bg_from_date = $bg_from_date;
$ac_bg->bg_to_date = $bg_to_date;
$ac_bg->bg_certificate = $bgCertImgName;
$ac_bg->save();
}
}
You haven't posted full code here, but I believe before loop you somehow set $ac_bg variable. So looking at your code you create one record and update it in every next loop iteration.
So to fix this you should probably do something like this:
foreach ($request->file('bg_certificate') as $key => $file) {
$ac = new Ac(); // don't know what's the exact model class here
Then in every loop iteration you will create new record instead of updating it.
Related
I am working on a JSON file in which I want to increment instead of overwriting the data. However I cannot seem to do this (since it keeps on overwriting instead of adding data with an incremented ID).
The code underneath is: database_json.php (as u can see I include it in saveJson.php)
$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];
the below is the code of the file saveJson.php contains the following code:
// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
}
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
}
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
// a lot of variables that aren't related to the problem
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
}
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $_POST['id'],
// more not related to problem variables
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
so, what I wish for: To increment the IDs and NOT to overwrite the data.
I already did some research and didn't find any useful information besides this --> Auto increment id JSON, but to me it looks like I have the same principle applied.
I have a custom post with up to 13 images. Beside some other information, I write the image names and titles into a txt-file, whereby each post information is stored on a separate line.
So far everything works fine execept when the first post has eg. 8 images and the second post has 5 images, than in the txt-file I have the first 5 images from the second post but also the 3 last images from the first post, even though they should be "empty" in the second line in the txt-file.
To get the image information from the wordpress database I have following code:
foreach($images as $image)
{
$path = parse_url(wp_get_attachment_url( $image ), PHP_URL_PATH);
$files_all['images'][] = $files['images'][] = ABSPATH . $path;
$files['title'][] = get_the_title($image);
$files['imagename'][] = basename(ABSPATH . $path);
}
if(!empty($files['imagename'][0]))
{
$pic1_filename = $files['imagename'][0];
$pic1_title = $files['title'][0];
}
if(!empty($files['imagename'][1]))
{
$pic2_filename = $files['imagename'][1];
$pic2_title = $files['title'][1];
}
if(!empty($files['imagename'][2]))
{
$pic3_filename = $files['imagename'][2];
$pic3_title = $files['title'][2];
}
if(!empty($files['imagename'][3]))
{
$pic4_filename = $files['imagename'][3];
$pic4_title = $files['title'][3];
}
if(!empty($files['imagename'][4]))
{
$pic5_filename = $files['imagename'][4];
$pic5_title = $files['title'][4];
}
if(!empty($files['imagename'][5]))
{
$pic6_filename = $files['imagename'][5];
$pic6_title = $files['title'][5];
}
if(!empty($files['imagename'][6]))
{
$pic7_filename = $files['imagename'][6];
$pic7_title = $files['title'][6];
}
if(!empty($files['imagename'][7]))
{
$pic8_filename = $files['imagename'][7];
$pic8_title = $files['title'][7];
}
if(!empty($files['imagename'][8]))
{
$pic9_filename = $files['imagename'][8];
$pic9_title = $files['title'][8];
}
if(!empty($files['imagename'][9]))
{
$pic10_filename = $files['imagename'][9];
$pic10_title = $files['title'][9];
}
if(!empty($files['imagename'][10]))
{
$pic11_filename = $files['imagename'][10];
$pic11_title = $files['title'][10];
}
if(!empty($files['imagename'][11]))
{
$pic12_filename = $files['imagename'][11];
$pic12_title = $files['title'][11];
}
if(!empty($files['imagename'][12]))
{
$pic13_filename = $files['imagename'][12];
$pic13_title = $files['title'][12];
}
The txt-File code looks as follows:
$txt .= "IDX3.01#Wordpress_4.6.2#".$proptype."#".$prop_label."#".$prop_status."#".$property_id."###".$address."#".$zip."#".$propcity."##".$country."###".$avail_from."#".$title.'#'.$post_description."#".$sale_price."#".$rent_price."##SELL#CHF###".$rooms."##".$property_size."#".$property_land."###".$property_year."#######".$garage."###".$distance_public_transport."#".$distance_shop."#".$distance_kindergarten."#".$distance_school1."#".$distance_school2."#".$pic1_filename."#".$pic2_filename."#".$pic3_filename."#".$pic4_filename."#".$pic5_filename."#".$pic1_title."#".$pic2_title."#".$pic3_title."#".$pic4_title."#".$pic5_title."######".$videos_name."#".$videos_title."##".$docname."#".$doctitle."##".$object_link."#agncyidxxxccc#Mischler Immobilien AG###Moosmattstrasse 23#6005#Luzern#CH#0413620101###info#mischler-immobilien.ch##".$agent_name."#0413620101#####".$pic6_filename."#".$pic7_filename."#".$pic8_filename."#".$pic9_filename."#".$pic6_title."#".$pic7_title."#".$pic8_title."#".$pic9_title."################################################".$pic10_filename."#".$pic11_filename."#".$pic12_filename."#".$pic13_filename."#".$pic10_title."#".$pic11_title."#".$pic12_title."#".$pic13_title."##################################".PHP_EOL;
The # are just separators within the file.
What did I miss here?
i'm trying to add a new view (called lista) of "spsoccer" joomla component.
I've followed this post but i've got the following error:
"1146
Table 'labaitac5.#__spsoccer_lista' doesn't exist SQL=SHOW FULL COLUMNS FROM `#__spsoccer_lista`"
This is what I did:
I copied the structure of my other view (called tournament)
So now I have:
directory structure
I changed view.html.php in the Lista folder with the appropriate class:
<?php
class SpsoccerViewLista extends FOFViewHtml{
public function display($tpl = null){
// Get model
$model = $this->getModel();
// get item
$this->item = $model->getItem();
//Joomla Component Helper & Get LMS Params
$app = JFactory::getApplication();
$menuItem = $app->getMenu()->getActive();
$this->show_group = $menuItem->params->get('show_group', 1);
// Get last played match
$this->last_played_match = $model->getLastPlayedMatch($this->item->spsoccer_tournament_id);
$this->match_banner = (!empty($this->last_played_match->image)) ? 'style="background-image: url(' . $this->last_played_match->image . ')"' : '' ;
// get groups of this tournament
$this->groups = $model->getTournamentGroups($this->item->spsoccer_tournament_id);
foreach ($this->groups as $this->group) {
$this->group->title = (strpos($this->group->slug, 'uncategory') !== FALSE) ? JText::_('COM_SPSOOCER_GROUP') : $this->group->title;
$this->group->ungroup = (strpos($this->group->slug, 'uncategory') !== FALSE) ? 'ungroup' : '';
}
// Get Sessions by Tournament ID
$this->sessions = $model->getTournamentSessions($this->item->spsoccer_tournament_id);
// Get Matches By Session and Tournament
foreach ($this->sessions as &$this->session) {
$this->session->session_matches = $model->getSessionMatches($this->session->spsoccer_session_id, $this->item->spsoccer_tournament_id);
$this->session->title = (strpos($this->group->slug, 'uncategory') !== FALSE) ? JText::_('COM_SPSOOCER_SESSION') : $this->session->title;
foreach ($this->session->session_matches as &$this->session->session_match) {
//Get team one info
$this->session->session_match->team_one_info = $model->getTeamInfoById($this->session->session_match->teamone);
$this->session->session_match->team_one_url = JRoute::_('index.php?option=com_spsoccer&view=gameteam&id=' . $this->session->session_match->team_one_info->spsoccer_gameteam_id . ':' . $this->session->session_match->team_one_info->slug . SpsoccerHelper::getItemid('gameteams'));
//Get team two info
$this->session->session_match->team_two_info = $model->getTeamInfoById($this->session->session_match->teamtwo);
$this->session->session_match->team_two_url = JRoute::_('index.php?option=com_spsoccer&view=gameteam&id=' . $this->session->session_match->team_two_info->spsoccer_gameteam_id . ':' . $this->session->session_match->team_two_info->slug . SpsoccerHelper::getItemid('gameteams'));
//Match Date
$this->session->session_match->match_date = JHtml::date($this->session->session_match->date, 'd M Y');
//Match Month
$this->session->session_match->match_time = date ('H:i',strtotime($this->session->session_match->time));
//Match Location
$this->session->session_match->match_location = $model->getVanueInfoById($this->session->session_match->spsoccer_vanue_id);
} //END:: $this->session->session_matches
//Get Sessions Played Match
$this->session->played_matches = $model->getSessionPlayedMatches($this->session->spsoccer_session_id, $this->item->spsoccer_tournament_id);
foreach ($this->session->played_matches as &$this->session->played_match) {
// Generate Match URL
//$this->session->played_match->team_one_info = $model->getTeamInfoById($this->session->played_match->teamone);
$this->session->played_match->url = JRoute::_('index.php?option=com_spsoccer&view=match&id=' . $this->session->played_match->spsoccer_match_id . ':' . $this->session->played_match->slug . SpsoccerHelper::getItemid('matches'));
//Get team one info
$this->session->played_match->team_one_info = $model->getTeamInfoById($this->session->played_match->teamone);
$this->session->played_match->team_one_url = JRoute::_('index.php?option=com_spsoccer&view=gameteam&id=' . $this->session->played_match->team_one_info->spsoccer_gameteam_id . ':' . $this->session->played_match->team_one_info->slug . SpsoccerHelper::getItemid('gameteams'));
//Get team two info
$this->session->played_match->team_two_info = $model->getTeamInfoById($this->session->played_match->teamtwo);
$this->session->played_match->team_two_url = JRoute::_('index.php?option=com_spsoccer&view=gameteam&id=' . $this->session->played_match->team_two_info->spsoccer_gameteam_id . ':' . $this->session->played_match->team_two_info->slug . SpsoccerHelper::getItemid('gameteams'));
//Match Date
$this->session->played_match->match_date = JHtml::date($this->session->played_match->date, 'd M Y');
//Match Month
$this->session->played_match->match_time = date ('H:i',strtotime($this->session->played_match->time));
//Match Location
$this->session->played_match->match_location = $model->getVanueInfoById($this->session->played_match->spsoccer_vanue_id);
}
} // END:: foreach $this->session->session_matches
// Team Standings
// $this->teams_ids = array();
// foreach ($this->groups as $this->group) {
// $group_team_ids = json_decode($this->group->spsoccer_gameteam_id);
// foreach ($group_team_ids as &$group_team_id) {
// $this->teams_ids[] = $group_team_id;
// }
// }
// $this->uniqie_teams_ids = array_unique($this->teams_ids);
// // Team info
// $this->unique_team_info = array();
// foreach ($this->uniqie_teams_ids as $this->uniqie_teams_id) {
// $this->unique_team_info[] = $model->getTeamInfoById($this->uniqie_teams_id);
// //print_r($this->team_info);
// }
// Point Table
foreach ($this->groups as &$this->sgroup) {
//title
$this->sgroup->uncategory = (strpos($this->group->slug, 'uncategory') !== FALSE) ? 'uncategory' : '';
// Get Timeline
$point_table_decode = json_decode($this->sgroup->point_table);
if ($point_table_decode) {
// Point table
$teams = $point_table_decode->team;
$playeds = $point_table_decode->played;
$wons = $point_table_decode->won;
$draws = $point_table_decode->draw;
$losts = $point_table_decode->lost;
$gforwards = $point_table_decode->gforward;
$gagainsts = $point_table_decode->gagainst;
$avgs = $point_table_decode->avg;
$ptss = $point_table_decode->pts;
$point_tables = array();
$pt_key = 0;
foreach ($teams as $id => $team) {
$team_info = $model->getTeamInfoById($teams[$id]);
$team_title = $team_info->title;
$team_logo = $team_info->logo;
$point_tables[$pt_key] = array(
'team_name' => $team_title,
'team_logo' => $team_logo,
'plays' => $playeds[$id],
'wons' => $wons[$id],
'draws' => $draws[$id],
'losts' => $losts[$id],
'gforwards' => $gforwards[$id],
'gagainsts' => $gagainsts[$id],
'avgs' => $avgs[$id],
'ptss' => $ptss[$id],
);
$pt_key ++;
}
$this->sgroup->point_tables = $model->msort($point_tables, array('ptss'));
} // END:: has point table
} // END:: foreach $this->groups
// Match Location
$this->match_location = $model->getVanueInfoById($this->item->spsoccer_tournament_id);
return parent::display($tpl = null);
}
}
Can anyone help me, please?
This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 1 year ago.
Basically I want to make a download button for my project that will produce different csv files (one csv file per table) in memory and zip before download. It works fine but the problem is that I am only getting one row (the last result) on each mysql_fetch_array where it is supposed to return rows depending on how many are stored in the database. This code is depreciated, sorry for that.
Here is my code:
<?php
require("../includes/connection.php");
require("../includes/myLib.php");
//get the ID that is passed
$ID = $_REQUEST['q'];
$ID = xdec($ID);
//All queries to fetch data
$query = mysql_query("SELECT * FROM `ge2`.`projects` WHERE `projects`.`proj_id`='$ID'");
$query2 = mysql_query("SELECT * FROM `ge2`.`attributes` WHERE `attributes`.`proj_id`='$ID'");
$query3 = mysql_query("SELECT * FROM `ge2`.`category` WHERE `category`.`proj_id`='$ID'");
$query4 = mysql_query("SELECT * FROM `ge2`.`multipletarget` WHERE `multipletarget`.`proj_id`='$ID'");
$query5 = mysql_query("SELECT * FROM `ge2`.`data_cut` WHERE `data_cut`.`proj_id`='$ID'");
$query6 = mysql_query("SELECT * FROM `ge2`.`raw` WHERE `raw`.`proj_id`='$ID'");
//getting all array
while ($row = mysql_fetch_array($query)) {
$proj_alias = $row['proj_alias'];
$proj_id = $row['proj_id'];
$date_added = $row['date_added'];
}
while ($row1 = mysql_fetch_array($query2)) {
$attrib_param_id = $row1['param_id'];
$attrib_proj_id = $row1['proj_id'];
$attrib_cat_id = $row1['cat_id'];
$attrib_val_id = $row1['val_id'];
$attrib_name = $row1['name'];
$attrib_isCust = $row1['isCust'];
}
while ($row2 = mysql_fetch_array($query3)) {
$category_cat_id = $row2['cat_id'];
$category_name = $row2['name'];
$category_proj_id = $row2['proj_id'];
$category_desc = $row2['desc'];
}
while ($row3 = mysql_fetch_array($query4)) {
$multipletarget_id = $row3['id'];
$multipletarget_proj_id = $row3['proj_id'];
$multipletarget_mtarget1 = $row3['mtarget1'];
$multipletarget_mtarget2 = $row3['mtarget2'];
}
while ($row4 = mysql_fetch_array($query5)) {
$data_cut_id = $row4['id'];
$data_cut_proj_id = $row4['proj_id'];
$data_cut_name = $row4['name'];
$data_cut_param = $row4['param'];
$data_cut_lvl = $row4['lvl'];
$data_cut_val = $row4['val'];
}
while ($row5 = mysql_fetch_array($query6)) {
$raw_id = $row5['raw_id'];
$raw_proj_id = $row5['proj_id'];
$raw_p_id = $row5['p_id'];
$raw_url = $row5['url'];
$raw_ip = $row5['ip'];
$raw_pos = $row5['pos'];
$raw_datetaken = $row5['datetaken'];
$raw_used = $row5['used'];
$raw_fdc_id = $row5['fdc_id'];
$raw_dq = $row5['dq'];
}
// some data to be used in the csv files
$records = array(
$proj_alias, $proj_id, $date_added
);
$records2 = array(
$attrib_param_id, $attrib_proj_id, $attrib_cat_id, $attrib_val_id, $attrib_name, $attrib_isCust
);
$records3 = array(
$category_cat_id, $category_name, $category_proj_id, $category_desc
);
$records4 = array(
$multipletarget_id, $multipletarget_proj_id, $multipletarget_mtarget1, $multipletarget_mtarget2
);
$records5 = array(
$data_cut_id, $data_cut_proj_id, $data_cut_name, $data_cut_param,$data_cut_lvl,$data_cut_val
);
$records6 = array(
$raw_id, $raw_proj_id, $raw_p_id, $raw_url,$raw_ip,$raw_pos,$raw_datetaken,$raw_used,$raw_fdc_id,$raw_dq
);
//making an array to be used in loop
$set = array($records,$records2,$records3,$records4,$records5,$records6);
//names to be named for each csv file
$names = array('projects', 'attributes', 'category', 'multipletarget', 'data_cut', 'raw');
// create zip file
$zipname = $proj_alias;
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
// loop to create csv files
$n = 0;
foreach ($set as $setk => $sets) {
$n += 1;
$fd = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $fd) {
die('Failed to create temporary file');
}
fputcsv($fd, $sets);
// return to the start of the stream
rewind($fd);
// add the in-memory file to the archive, giving a name
$zip->addFromString('BrainLink-' . $proj_alias . "-" . $names[$setk] . '.csv', stream_get_contents($fd));
//close the file
fclose($fd);
}
// close the archive
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname.'.zip');
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
// remove the zip archive
// you could also use the temp file method above for this.
unlink($zipname);
?>
Thanks in advance.
Well, it seems that you're independently iterating over all query results and overwriting the variables over and over again. So in the end, you have only last table results to work with.
You might try using JOIN OR UNION SELECT in MySQL to get all the items in one big query result row:
$query = mysql_query('SELECT proj.*, attrs.*
FROM `projects` AS proj
JOIN `attributes` AS attrs ON (attrs.project_id=proj.project_id)
<..more tables to join in the same manner..>
WHERE proj.`proj_id`= ' . $projectId);
And then, you'll just have to iterate only over a single query resource.
while ($row = mysql_fetch_array($query)) {
//your code here
}
Note, that if tables being JOIN'ed have the same column names, they will "overwrite" each other and you'll have to rename them yourself "on the fly".
Like so:
SELECT proj.field, proj.another_field, proj.conflicting_field_name AS unique_field_name
I did not read all of your code, but in each while loop, you only save last record. It should be something like this.
while($row = mysql_fetch_array($query)){
$proj_alias[] = $row['proj_alias'];
$proj_id[] = $row['proj_id'];
$date_added[] = $row['date_added'];
}
and the others like above.
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