Insert Multiple Rows in Laravel (Image Upload Issues) - laravel-8

In my application, I have faced several issues when I try to insert multiple rows of data into a database in laravel 8. Basically this issues is related to image upload. I have add related code to get help.
Controller View:
foreach($request->param_img as $key => $param_img){
$data = new PortfolioParam;
$data->param_desc = $request->param_desc[$key];
if($request->hasfile('param_img')){
$file = $request->file('param_img');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('upload/portfolio_param/', $filename);
$portfolio->param_img = $filename;
}
$data->portfolio_id = $portfolio->id;
$data->save();
}
Blade View:
<td class="pl-0 border-0">
<textarea class="form-control" name="param_desc[]" id="" cols="30" rows="3"></textarea>
</td>
<td class="border-0">
<input type="file" class="form-control" name="param_img[]">
</td>
Error
Call to a member function getClientOriginalExtension() on array
How can I get rid of this problems??

You have looped through the image but you have not used it in your image uploading code. You are still using the request data. Check this out, hopefully it helps.
// $file = $request->file('param_img');
$file = $param_img;
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('upload/portfolio_param/', $filename);
$portfolio->param_img = $filename;

Related

Empty post value : CodeIgniter

While uploading the file through codeigniter, I am getting the following error:
My file upload result is:
My Controller function is below:
public function Upload files($data='')
{
ini_set("display_errors",1); // I added so it would help me show errors
error_reporting(E_ALL);
print_r($_POST);exit('I am in the tp');
$config['upload_path'] = 'assets/images/uploads/';
//$config['allowed_types'] = 'gif|jpg|png';
//$config['max_size'] = 100;
//$config['max_width'] = 1024;
//$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);exit('The first loop');
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
print_r($data);exit();
$this->load->view('upload_success', $data);
}
}
And my view file:
<div id="Upload_div">
<?php //echo $error;?>
<form action="<?php echo site_url() ?>/Admin/Upload_files/" method="POST" enctype="multipart/form-data">
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="userfile"><br><br>
<input type="submit" name="submit" value="submit">
</form>
</div>
Can anyone help me figure out why post value is empty?
Thanks
$_POST does not contain any file data.
Remove the line
print_r($_POST);exit('I am in the tp');
And then tell us what happens.

Notice: Undefined variable: on line 24

I have the code:
if(isset($_POST['id'])){ $res = $_POST['id']; }
if(isset($_POST['ora2'])){ $oratwo = $_POST['ora2']; }
$operator = $_SESSION['login'];
$order = "
UPDATE `frontdes_dep`.`flux_receptie`
SET `status_preluare` = 'ALOCAT', `ora_preluare` =$oratwo, `operator_preluare` =$operator
WHERE `flux_receptie`.`id` =$res";
$result = mysqli_query($connection, $order);
When I press the submit button which take actions above, it returns me error:
( ! ) Notice: Undefined variable: oratwo in C:\wamp\www\interfata_client.php on line 24
The code is working because when I look into DB, the columns populate with values.
Line 24 is the line with $order = ...
The submit is in an echo:
echo "<div id='example3'>
<form style='padding:15px 0px 0px 0px' id='interfata' name ='interfata' method='POST' action='interfata_client.php' enctype='multipart/form-data'>
<input type='hidden' name='id' value='$res[0]'>
<input type='hidden' name='ora2' value='now()'>
<input type='submit' name='name' value='ALOCARE'>
</form>
<td><center>preluat de:<p><b>$res[8]</center></b></td>
</tr>
</div>
<br>
";
Does anynone know what am I doing wrong? I have WAMP installed.
Thanks! :)
There are 2 ways to get rid of this issue , The first one is to ignore the issue by turning of Notice exceptions .
error_reporting(E_ALL ^ E_NOTICE );
Or try the second solution below.
Notice : check whether the value is coming up from the form ('ora2')
before trying the second one.
Your code
if(isset($_POST['ora2'])){ $oratwo = $_POST['ora2']; }
Updated code
if(isset($_POST['ora2'])){
$oratwo = isset($_POST['ora2']) ? $_POST['ora2'] : '';
}

Method not receiving attributes from shortcode call, general OOP problems

The method OpenMods that you see below, is supposed to take an array generated by an fgetcsv function, and put it into an HTML table. __construct is supposed to, as is typically the case, define the attributes for the class, and shortcode is supposed to take two attributes from the shortcode, and if mods comes back, it is supposed to call another function in the class.
OpenMods did function when it was outside of a class, without the class attribute calls, so I'm fairly certain that isn't the source of my problem. My problem most likely lies within __construct and shortcode; However please don't overlook OpenMods as it may contain errors that are contributing to the problem, I'm just giving my estimation which isn't worth much since I'm having to ask to for help.
This is an example of the shortcode I'm trying to make work:
[priceguide file=’test.csv’ type=’mods’]
class CsvImporter
{
private $parse_header;
private $header;
private $delimiter;
private $length;
//--------------------------------------------------------------------
function __construct($parse_header=false, $delimiter="\t", $length=8000)
{
add_shortcode( 'priceguide', array( $this, 'shortcode' ) );
$this->parse_header = $parse_header;
$this->delimiter = $delimiter;
$this->length = $length;
}
//--------------------------------------------------------------------
public function shortcode($atts) {
$attributes = extract( shortcode_atts( array(
'file' => '',
'type' => '',
), $atts ));
if ($attributes['mods'])
{
$this->OpenMods($attributes['file']);
}
}
//--------------------------------------------------------------------
function OpenMods($file) {
ob_start();
$fp = fopen(plugin_dir_path( __FILE__ ) . $file , "r" );
if ($this->parse_header)
{
$header = fgetcsv($fp, $this->length, $this->delimiter);
}
// table header and search html
echo('<input type="text" class="search" id="search" placeholder="Search">');
echo('<br>');
echo('<table id="table"> <tr class="hidden">
<th><b>
Name</b>
</th>
<th><b>
Cheese</b>
</th>
<th><b>
Price</b>
</th>
<th><b>Vote</b>
</th>
</tr>
<tbody>');
// integer for drop down/price submit
$a = 1;
// set values for table data
while ($header !== FALSE) {
$name = $header[0];
$quanid = $header[2];
$table = $header[3];
unset($header[2]);
unset($header[3]);
$cssId = 'row-'.$a;
$a++;
//generate HTML
echo('<tr>');
foreach ($header as $index=>$val) {
echo('<td>');
echo htmlentities($val, ENT_QUOTES);
echo('</td>');
}
// query to get item prices
$sql = "SELECT ItemID, Price
FROM {$table}
WHERE ItemID = %d
GROUP BY Price
ORDER BY COUNT(*) DESC LIMIT 1";
global $wpdb;
$results = $wpdb->get_var( $wpdb->prepare( $sql, $quanid));
// put the results in the table
echo('<td>');
print_r($results);
echo('</td>');
// HTML for hidden row/price submission
echo('<td>
<button class="toggler" data-prod-cat="' . $cssId . '">Vote</button>
</td>');
echo('</tr>');
echo('<tr class="cat' . $cssId . ' hidden" style="display:none">');
echo('<td colspan="4" style="white-space: nowrap">Enter ' . $name . ' Price:
<form action="" name="form' . $quanid . '" method="post"><input type="text" id="' . $quanid . '" maxlength="4" name="' . $quanid . '" value="price_input" class="input" />
<button id="submit" name="submit" class="submit" type="submit" value="Submit">Submit</button></form>
<?php
?>
</td>
</tr>');
wp_nonce_field('price_input');
}
echo("</table>");
fclose($fp);
return ob_get_clean();
}
}
Based on OP comment, the problem is, the object can not created and in this case, __constructor() will not run, and add_shortcode( 'priceguide', array( $this, 'shortcode' ) ); will never triggered.
There are two solutions. One, if you are make the shortcode method to static, and add this in your functions.php file:
add_shortcode( 'priceguide', 'CsvImporter::shortcode' ) );
The second option, if you do not want to make it static if you instantiate an object from your class, before anythings happens. In your functions.php
add_action('init', 'my_init');
global $CsvImporter;
function my_init() {
global $CsvImporter;
$CsvImporter = new CsvImporter();
}
In this case, when no output send to the buffer, you create a new CsvImporter object, so the __construct() will run, so shortcode will registered.

Joomla 3.3 MVC file/pdf upload in custom component backend

I want to upload a pdf from a custom component from backend in the edit mode.
the state now is,
1.- either the pdf is uploaded correctly but the file name is not written in the database,
2.- or the file name is written in the data base, but the pdf is not seen by JFactory::getApplication()->input;
I found out is has with enctype="multipart/form-data" to do.
In case 1.- enctype="multipart/form-data" is in and the pdf is uploaded
in case 2.- the pdf file name is written in the data base.
What to do know ? I need both, of course.
Here so code, it is a little component com_job with MVC structure under Joomla! 3.3:
here just the part file administrator/components/com_job/views/tmpl/edit.php
with the enctype="multipart/form-data"
<form method="post" action="<?php echo JRoute::_('index.php?option=com_job&layout=edit&id='.(int) $this->item->id); ?>" id="adminForm" name="adminForm" enctype="multipart/form-data">
<fieldset class="adminform">
<legend><?php echo JText::_( 'Details' ); ?></legend>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('title'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('title'); ?>
</div>
</div>
....
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('upload_pdf'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('upload_pdf'); ?>
</div>
</div>
........
here a part of the xml file administrator/components/com_job/models/forms/job.xml
<?xml version="1.0" encoding="utf-8"?>
...
<field
id="title"
name="title"
type="text"
required="true"
label="Title"
description="title_Desc"
class="inputbox"
size="40"/>
<field
id="upload_pdf"
name="upload_pdf"
type="file"
required="false"
label="Upload_pdf"
description="upload_pdf_Desc"
class="inputbox"
size="40"
accept="application/pdf"/>
.....
here the controller administrator/components/com_job/controllers/job.php
jimport('joomla.application.component.controlleradmin');
jimport('joomla.application.component.controllerform');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
class JobControllerJob extends JControllerForm
{
public function save()
{
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform', null);
$files['upload_pdf']['name'] = JFile::makeSafe($files['upload_pdf']['name']);
if (!empty($files['upload_pdf']['name'])) {
$pdf_path = JPATH_ROOT . '/images/upload_pdf';
if (!JFolder::exists($pdf_path)) {
$status = JFolder::create($pdf_path);
if (!$status) {
JError::raiseWarning(100, JText::_('could not create directory pdf'), '');
}
}
$file_path = JPath::clean($pdf_path . '/' . strtolower($files['upload_pdf']['name']));
$status = JFile::upload($files['upload_pdf']['tmp_name'], $file_path);
if (!$status) {
JError::raiseWarning(100, JText::_('could not copy pdf'), '');
}
}
return parent::save();
}
}
where is the error ? I tried to put enctype="multipart/form-data" in the form in job.xml (models), but it didn't work.
I found a temporally solution, in the save function in the controller, I add this code:
//$jform = $jinput->get(jform, null);
$pdf_filename = JFile::makeSafe($files['upload_pdf']['name']);
$jform = $_POST['jform'];
$tmp_pdf_filename = array('upload_pdf' => $pdf_filename);
$merged_jform = array_merge($jform,$tmp_pdf_filename);
$jinput->post->set('jform',$merged_jform);
the first line with $jinput didn't work. I tried many ways with $jinput, but nothing worked. So finally I used directly $_POST. Of course, it is not the right way, but at least it works.
here the full function save:
public function save()
{
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform', null);
$pdf_filename = JFile::makeSafe($files['upload_pdf']['name']);
if (!empty($pdf_filename)) {
$pdf_path = JPATH_ROOT . '/images/upload_pdf';
if (!JFolder::exists($pdf_path)) {
$status = JFolder::create($pdf_path);
if (!$status) {
JError::raiseWarning(100, JText::_('could not create directory pdf'), '');
}
}
$file_path = JPath::clean($pdf_path . '/' . strtolower($files['upload_pdf']['name']));
$status = JFile::upload($files['upload_pdf']['tmp_name'], $file_path);
if ($status) {
//$jform = $jinput->get(jform, null);
$jform = $_POST['jform'];
$tmp_pdf_filename = array('upload_pdf' => $pdf_filename);
$merged_jform = array_merge($jform,$tmp_pdf_filename);
$jinput->post->set('jform',$merged_jform);
} else {
JError::raiseWarning(100, JText::_('could not copy pdf'), '');
}
}
return parent::save();
}
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform');
$file = $files['upload_pdf'];
Try this...it is true method!!!
That should do the trick. The $file array then holds the following keys:
error
name
size
tmp_name
type

Deleting single item with submit from database results in two ID's and strings

When I try and delete an entry from the code below it seems to spew out two array values with different index numbers and will not delete the entry. If I click multiple times it finally gets the correct ID but only by some random chance.
Using echo var_dump($deleted) results in something like:
String(2) "10"
String(1) "7"
These can vary and seems to be random.
I have reduced my whole plugin to just the code below thinking that maybe some other submit query might be interfering with it. And still I get two ID's with unknown string assignments.
Any ideas?
function myplugin_update_page(){
global $wpdb;
$update_page_list = $wpdb->get_results('SELECT * FROM wp_update_page');
$active = $wpdb->get_var("SELECT * FROM wp_update_page WHERE active='on'");
echo '<form method="post" action=""><table>';
foreach ( $update_page_list as $update ) { ?>
<tr>
<td><input type="image" src="<?php echo plugin_dir_url(__FILE__).'images/delete.png'; ?>" name="delete[]" value="<?php echo $update->ID; ?>" /></td>
</tr>
</table>
</form>
</div>
<?php
}
if(isset($_POST['delete'])) {
$delete = $_POST['delete'];
foreach ($delete as $deleted) {
$wpdb->query("DELETE FROM wp_update_page WHERE ID = $deleted");
}
echo "<script type='text/javascript'>window.location=document.location.href;</script>";
}
}