Undefined index:jawaban - php

I want to input multiple data to database using array, but I got an error message. The code are in the following bellow :
ClusterController
$jawaban = $request->jawaban;
$data = [];
if($jawaban != null || $jawaban == false){
for($i=1; $i<=count($jawaban['jawaban']); $i++){
$data[] = array('jawaban' => $jawaban[$i]['jawaban']);
}
$store = Soal::where('cluster_id', $id)->update($data);
return dd($store);
}
showexam.blade.php
<form action="/jawaban/store/{{$model[$i]->id}}" method="post" enctype="multipart/form-data">
#csrf
<table id="datatable" style="width:100%">
<tbody>
<tr>{{$i+1}}. </tr>
<tr>{{$model[$i]->soal}}</tr>
<ol type="A" style="">
<li> {{$model[$i]->A}}</li>
<li> {{$model[$i]->B}}</li>
<li> {{$model[$i]->C}}</li>
<li> {{$model[$i]->D}}</li>
<li> {{$model[$i]->E}}</li>
</ol>
<input list="browsers" name="jawaban[]">
<datalist id="browsers">
<option value="A">
<option value="B">
<option value="C">
<option value="D">
<option value="E">
</datalist>
#endfor
<button type="submit" class="btn btn-primary text-right" id="modal-btn-save">Done</button>
</form>

count($jawaban['jawaban'])
You already have an array called jabawan that you retrieved with $jawaban = $request->jawaban;
That jabawan will have a normal counting array $jabawan = ['A', 'B']
It will not have an index called jabawan.
If you had done something like
$jabawan = post();
You could use your code, but you can just use
for($i=0; $i<count($jawaban); $i++){
$data[] = array('jawaban' => $jawaban[$i]);
}
Change Soal::where('cluster_id', $id)->update($data);
into
if ($soal_model = Soal::find( $id )) {
$soal_model->update($data);
}
The problem is that you're never calling get() on the query object, or a first() on the collection that the get() returns.
By using find() You get an object back or null if it doesn't exist.
By wrapping that in an if statement the update will only be executed on an existing object, preventing errors on trying to update a null value.
Also, you cannot return a dd().
dd stands for 'dump and die' I believe, at least that is what I read into it because that's what it does.
It dumps the data and then kills the process. So all laravel return handlers won't get called after your dd() call. You killed the process.

Related

How to insert two different values together into database whereas checkbox value and another input value such as quantity

I'm trying to insert two different value one is from a checkbox and one from different value such as quantity of the checkbox value beside it. I'm using foreach below as I am retrieving the books name saved into the database into the checkbox.
#foreach($data as $data)
<form action="{{url('/bookreservation')}}" method="post">
#csrf
<div class="row col-12">
<div>
<p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="{{$data->title}}"/>{{$data->title}}
<input type="number" name="prod_qty[]" min="1" value="1"class="form-control">
</div>
#endforeach
</div>
</form>
When I use the code below it successfully inserts the data into my database, however it only saves the prod_name since that is the only thing I implode and inserted to my database.
public function bookreservation(Request $request)
{
$data = new bookreservation;
$data->name=$request->name;
$data->email=$request->email;
$data->phone=$request->phone;
$data->address=$request->address;
$data->date=$request->date;
$data->time=$request->time;
$prod_qty = $request->prod_qty;
$selected_products = $request->prod_name;
$products = implode(" ",$selected_products);
$data->products=$products;
$data->save();
return redirect()->back();
}
When I try to implode it together it gives me an error that "implode() expects at most 2 arguments, 3 given"
$prod_qty = $request->prod_qty;
$selected_products = $request->prod_name;
$products = implode($prod_qty," ",$selected_products);
$data->products=$products;
and if I remove " " inside the implode a different error is given "implode(): Argument #1 ($separator) must be of type string, array given" because I want to save both as one value and be inserted into the database as one as well and not separately.
What should I do to save two different values into one. Where prod_qty is beside or before the selected_products like 32 JasminBooks and if they insert/select another different value like 5 KnowHowBooks the result will be "32 JasminBooks, 5 KnowHowBooks," in the database and both are not separated.
First of all, there seems mistake in html structure, you are using forEach loop, which has form inside it and it's end statement is before "form" end tag.
You may follow html structure something like this:
<form action="{{url('/bookreservation')}}" method="post">
<?php foreach ($content as $row):?>
<tr>
<td><input type="text" class="form-control" value="<?php echo $row['title']?>" name="title[]"></td>
<td><input type="text" class="form-control" value="1" name="qty[]"></td>
</tr>
<?php endforeach;?>
<button type="submit" name="submit" value="Submit">Submit</button>
</form>
Then on API controller you may do something like this to iterate over collection and insert record one by one into database:
for($i=0; $i<count($_POST[title]); $i++) {
if(isset($_POST[$i][title])) {
//here goes insert statement
}
}

Laravel 7 - How to insert multiple data to mysql database

I am trying to insert data into database. But i don't know how to insert multi select checkbox data into the mysql database.
Controller
public function create(Request $request)
{
try {
$id_student = $request->get('id_student');
$consecutive = DB::select('SELECT SUM(idRecord) FROM record GROUP BY idRecord');
$final_consecutive = sprintf("%04d", $consecutive);
foreach($request->select as $data)
{
Records::create($data);
}
return back()->with('success', 'Constancia creada correctamente');
} catch (\Illuminate\Database\QueryException $e) {
$message = $e->getMessage();
if (strpos($message, "Duplicate entry")) {
return back()->with('err', 'Esta constancia ya ha sido creada');
}
if (strpos($message, "1366 Incorrect integer value: '' for column 'idGrupo'")) {
return back()->with('err', 'Debe seleccionar un grupo para poder continuar');
}
return back()->with('err', $message);
}
}
View
#foreach ($group->students as $student)
<tr>
<td class="align-middle text-center">
<input class="form-control" type="text" name="nombre" value="{{$student->lastName}} {{$student->Names}}" disabled>
</td>
<td class="align-middle text-center">
<input class="form-control form-control-sm" type="text" name="grade" value="{{isset($student->pivot->grade)?$student->pivot->grade:''}}" placeholder="grade" disabled>
</td>
<form action="{{url('/Create/Records')}}" method="POST">
<input class="form-control form-control-sm" type="hidden" name="id_student" value="{{$student->id_student}}" >
<td class="align-middle text-center">
<input id="select" type="checkbox" name="select[]">
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-sm btn-outline-success">Save</button>
</div>
What I tried to do was use a select checkbox and then in the Controller I passed it as an array in the foreach loop, but honestly I think I'm nowhere close to figuring it out... Other than that the consecutive is automatically generated and I don't know how to pass it to the array as well.
I get this error by the way:
Argument 1 passed to Illuminate\Database\Eloquent\Builder::create()
must be of the type array, string given
You should pass data to your Model like:
Records::create(['id_student' => $idStudent, 'consecutive' => $consecutive]);
Currently, you are giving like:
Records::create('string');
Which is not correct way to pass the data. That's why getting the error.
Create() take array as parameter.
When your foreach loop execute $data value 0 or 1 as string so that why error is given.
if you want to create in foreach loop then
foreach($request->select as $data)
{
Records::create(['field_name' => $data]);
}
by default multiple select checkbox will be converted to assoc array with name that ends with [] as its key for example your using so you can access it like:
$select = $_POST['select'];
then you can iterate through the values this is a plain php would suggest to use the laravel method as it offers more like security and filter this one is a simple and fast solution. But if you using an ajax submission you should always make sure that the parameter always ends with [] example you have a get request but still the same syntax applies to post method:
http://localhost?select[]=1&select[]=2
the same code will work as on top but for get request like this you will use:
$select = $_GET['select'];
haven't tried on laravel request object but I think the same conversion is being done when your using the Request instance you may try that as well just make sure you always end the parameter name with [] but if the name of all the checkbox is set to select it will just return a single string which the error means.

Adding data to mysql table in ZF2

This is the code for add action, This action adds subjectName(from subjects Table), totalMarks and Description (from SubjectMarks Table)
public function addAction() {
$postArray = $this->params()->fromPost();
$entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
This if condition is set true if data is entered and addbutton is clicked
if (isset($postArray['submit']) && $postArray['subjectName']) {
$subjectMarks = new SubjectMarks();
$subjectMarks->setSubject(
$entityManager->find('Application\Entity\Subjects', $postArray['subjectName'])
);
$subjectMarks->setClasses(
$entityManager->find('Application\Entity\Classes', $postArray['classId'])
);
$subjectMarks->setSubject(
$entityManager->find('Application\Entity\Subjects', $postArray['subjectId'])
);
$subjectMarks->setTotalMarks($postArray['totalMarks']);
$subjectMarks->setDescription($postArray['subjectMarksDesc']);
$entityManager->persist($subjectMarks);
$entityManager->flush();
return $this->redirect()->toUrl($this->getRequest()->getBaseUrl().'/subjectmarks/totalmarks/index');
}
First else is executed that runs the query and sends data to 'add' view in form of 'data'
else
{
$entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
$qb = $entityManager->createQueryBuilder();
$qb->select(array(
'subjectMarks.subjectMarkId as subjectMarkId',
'subjectMarks.totalMarks as totalMarks',
'subjectMarks.description as subjectMarksDesc',
'subject.subjectId as subjectId',
'subject.name as subjectName',
'class.classId as classId',
))
->from('Application\Entity\SubjectMarks', 'subjectMarks')
->leftJoin('subjectMarks.subject', 'subject')
->leftJoin('subjectMarks.classes', 'class');
$data = $qb->getQuery()->getScalarResult();
return new ViewModel(array(
'data' => $data,
)
);
}
}
This is the code for add.phtml 'FORM' which is called when 'else' part executes and query selects the data required, and send the written data back, where it is received by if() condition.
<form name="myForm" action="<?php echo $this->url('subjectmarks/totalmarks', array('action'=>'add'));?>" method="POST">
<input type="hidden" name="classId" value="<?php echo $this->data[0]['classId'];?>">
<input type="hidden" name="subjectId" value="<?php echo $this->data[0]['subjectId'];?>">
<input type="text" name="subjectName" >
<input type="text" name="totalMarks" >
<input required="required" type="text" name="subjectMarksDesc" >
<button type="reset" class="btn btn-primary" > <a style="color: white" href="<?php echo $this->basePath('subjectmarks/totalmarks/index');?>">Cancel</a></button>
<button type="submit" name="submit" class="btn btn-success">Submit</button>
The Problem is that totalMarks and subjectMarkDesc are added correctly, while the subjectName is taken id[0] of subject table, for any name that is entered.
The answer is simple, as we can see that subjectName is inserted as input and subjectId is hidden, so there is no direct relation i.e, that clarify which subjectName is assigned to the subjectId.
So putting a select HTML tag will solve the problem, e.g
<select name="addSubjectMarks">
<?php foreach ($this->data as $item):?>
Here we can see subjectId and subjectName are related, unlike the question
<option value="<?php echo $item['subjectId'];?> "> <?php echo $item['subjectName'];?> </option>
<?php endforeach; ?>
</select>
Similarly there in the controller, inside the if (isset($postArray['submit']) && $postArray['subjectName']) condition, we will only replace this code
$subjectMarks->setSubject(
$entityManager->find('Application\Entity\Subjects', $postArray['addSubjectMarks'])
);
with this code
$subjectMarks->setSubject(
$entityManager->find('Application\Entity\Subjects', $postArray['subjectName'])
);
$subjectMarks->setSubject(
$entityManager->find('Application\Entity\Subjects', $postArray['subjectId'])
);
and it will perfectly. The select tag will output only those subjectNames which are already present in the subject Table.

Looping through input array in Laravel 5

I have a basic UI where users can add a simple list with a label and a value. I want to loop through that list to store the data in a "Detail" model.
I have the following code.
Controller:
$details = $request->input('detail_label');
foreach($details as $key => $value)
{
if(!empty($request->input('detail_value.'.$key))) {
// if the detail has an existing ID
if($request->input('detail_id.'.$key)) {
$detail = Detail::find($request->input('detail_id.'.$key));
} else {
$detail = new Detail;
}
$detail->type = $request->input('detail_type.'.$key);
$detail->label = $request->input('detail_label.'.$key);
$detail->value = $request->input('detail_value.'.$key);
if($request->input('detail_privacy.'.$key) == 1) {
$detail->privacy = 1;
} else {
$detail->privacy = 0;
}
$user->details()->save($detail);
}
}
View:
#foreach($user->details as $detail)
<div class="detail">
<input type="hidden" name="detail_id[]" value="{{ $detail->id }}">
<label>Type
<select name="detail_type[]">
<option #if($detail->type == '1')selected #endif value="1">Phone</option>
<option #if($detail->type == '2')selected #endif value="2">Phone (mobile)</option>
<option #if($detail->type == '3')selected #endif value="3">URL</option>
<option #if($detail->type == '4')selected #endif value="4">Email</option>
</select>
</label>
<label>Label
<input type="text" name="detail_label[]" value="{{ $detail->label }}">
</label>
<label>Value
<input type="text" name="detail_value[]" value="{{ $detail->value }}">
</label>
<label>Private?
<input type="checkbox" name="detail_privacy[]" #if($detail->privacy == true) checked #endif value="1">
</label>
<label>Delete?
<input type="checkbox" name="detail_delete[]" value="{{ $detail->id }}">
</label>
</div><!-- / detail -->
#endforeach
Every aspect of my code works as I had planned except the detail_privacy field. It sets and unsets the boolean privacy attribute but it pays no attention to which $key I want. It always sets it according to the order in the loop. If I just set one detail to be private it will be first. If I set two, (whichever two), it will be the first and second.
Something is clearly wrong with my logic but I can't tell what.
Any help would be really appreciated. Thanks!
The reason it doesn't work is that non-checked checkboxes are not included in the post data. You may see it by dumping value of $request->input('detail_privacy').
To be able both to edit existing and add new details, you need to set keys on inputs in the form. Anything really, as long as you keep track of it. To make things easier you can add hidden input named same as the checkbox, so detail_privacy will be always present in the post data. For example:
#foreach ($user->details as $key => $detail)
<input type="hidden" name="detail_id[{{ $key }}]" value="{{ $detail->id }}">
...
<input type="hidden" name="detail_privacy[{{ $key }}]" value="0">
<input type="checkbox" name="detail_privacy[{{ $key }}]" #if($detail->privacy == true) checked #endif value="1">
...
#endforeach
If you add new fields dynamically ie. with javascript you need to respect those keys. Its quite simple though, just pass last value of $key to your js and you're set.
Also I would recommend different notation for input names: details[{{ $key }}][id] instead of detail_id[{{ $key }}]. This way controller action will become much simpler:
foreach ($details as $detail) {
if (! empty($detail['id'])) {
...
}
}
If the Boolean values are stored as TINYINTS in the Database (as in: 0 or 1); then perhaps taking out the Boolean true || false may resolve the Issue. Not Certain but guessing it's worth the try:
<!-- JUST TRY IT LIKE SO: #if($detail->privacy) checked #endif -->
<label>Private?
<input type="checkbox"
name="detail_privacy[]"
#if($detail->privacy) checked #endif value="1"
>
</label>
Or Hypothetically:
<!-- YOU MAY ALSO USE "1" LIKE SO: #if($detail->privacy==1) checked #endif -->
<label>Private?
<input type="checkbox"
name="detail_privacy[]"
#if($detail->privacy==1) checked #endif value="1"
>
</label>

Select columns from mysql table by given array in php(CodeIgniter).

I want to select columns form mysql table which I have selected names as input value. In my view, have to select column names as multiple input fields. In this selection option values are equals to column names in my “pass_due” table in database.
<form id="" name=" Passdue " action="<?=base_url('index.php/Passdue_ctrl/select')?>" method="post">
<div >
<input class="date-picker" id="report_date" name="report_date" value="" placeholder="Select Date"/>
<select multiple="" class="chzn-select" id=" " data-placeholder="Select sections " name="table_feilds">
<option value="" />
<option value="below_1" /> Below month
<option value="month_1_3" /> Month 1-3
<option value="month_3_6" /> Month 3-6
<option value="month_6_9" /> Month 6-9
<option value="over_9" /> Over 9 month
</select>
</div>
<div>
<button type="submit" class="btn btn-mini btn-info">Submit</button>
<button type="reset" id="reset" class="btn btn-mini btn-info">Reset</button>
</div>
</form>
This is function in my controller
Function select (){
$fld_name =$this->input->post('table_feilds');
$reportdate=$this->input->post('report_date');
$report=$this->Passdue_model->get_report_part($fld_name,$reportdate);
If($report){
$this->data['report_part']=$report;
$this->data['fld_name']=$fld_name;
$this->load->view('Passdue_other_view',$this->data);
}
}
In my model like this.
function get_report_part1($fld_name,$reportdate)
{
$this->db->select($fld_name);
$this->db->from(‘pass_due’);
$this->db->where('fld_actORinact_date <=',$reportdate);
$query = $this->db->get();
if($query){
return $query->result();
}
}
When I run this code it select all columns from table, not only selected ones. And also it shows error as
Invalid argument supplied for foreach() .
You can use this new model method to retreive data from your db.So insert this method into your model
function getDetail($tablename = '', $columns_arr = array(), $where_arr = array(), $limit = 0, $offset = 0)
{
$limit = ($limit == 0) ? Null : $limit;
if (!empty($columns_arr)) {
$this->db->select(implode(',', $columns_arr), FALSE);
}
if ($tablename == '') {
return array();
} else {
$this->db->from($tablename);
if (!empty($where_arr)) {
$this->db->where($where_arr);
}
if ($limit > 0 AND $offset > 0) {
$this->db->limit($limit, $offset);
} elseif ($limit > 0 AND $offset == 0) {
$this->db->limit($limit);
}
$query = $this->db->get();
return $query->result();
}
}
//These are include within controller methods
$fld_name =$this->input->post('table_feilds');
//you have to send your columns from your multiple select object as array.
//create column array
$arr_columns=array();
for($i=0,$i<=count($fld_name);$i++){
$arr_columns=array_push($fld_name)
}
$reportdate=$this->input->post('report_date');
//create where array
$arr_where=array('fld_actORinact_date <=' => $reportdate);
//retreive data
$datatable=‘pass_due’;
$report=$this->Passdue_model->getDetail($datatable,$arr_columns,$arr_where,0,0);
var_dump($report);
//finally dump_data set .it return array object.Then loop retrieved object.
then this will return what you expect.
Also like to advise you to use generalized model except using separate models for each & every tables.
use below code in form
<select multiple="multiple" class="chzn-select" id=" " data-placeholder="Select sections " name="table_feilds[]"> <!-- use [] for multiple values -->
and I don't see any foreach loop?
and first
echo '<pre>';print_r($fld_name);exit; before
$report=$this->Passdue_model->get_report_part($fld_name,$reportdate);
In your model return the query as follows
return $query->result_array();
In your controller get data by
data['fld_name']=$this->Passdue_model->get_report_part($fld_name,$reportdate);
$this->load->view('Passdue_other_view',$data);
In your view page
foreach($fld_name as $fld_name){?> <th><?php echo $fld_name['column_name '];?></th> <?php }?> </tr> </thead>

Categories