Cant get values of checkboxes in codeigniter - php

Im trying to insert multiple checkboxes but cant get their values in codeigniter 2
this is my code in View
<!-- Multiple Checkboxes (inline) -->
<div class="form-group">
<div class="col-md-4">
<label class="checkbox-inline" for="checkboxes-0">
<input type="checkbox" name="checkboxes[]" id="checkboxes-0" value="22">
Пентхаус
</label>
<br>
<!-- Text input-->
<div class="form-group">
<div class="col-md-8">
<input id="cena" name="cena[]" type="text" placeholder="Въведи цена" class="form-control input-md">
</div>
</div>
<label class="checkbox-inline" for="checkboxes-1">
<input type="checkbox" name="checkboxes[]" id="checkboxes-1" value="21">
Гараж/Паркомясто
</label>
<br>
<!-- Text input-->
<div class="form-group">
<div class="col-md-8">
<input id="cena" name="cena[]" type="text" placeholder="Въведи цена" class="form-control input-md">
</div>
</div>
This is my Model:
public function InsertCheckbox() {
$property_typesRequest = $this->input->post('checkboxes');
foreach($property_typesRequest as $value){
$this->db->insert_batch('property_type_details', $property_typesRequest);
}
}
in Controller i just use this:
$this->estate_m->InsertCheckbox();
And this going insert 0 in database, when i var_dump $property_typesRequest theres shows bool(false). I cant get values of checkboxes...
EDIT...
I have try to edit my code but still no result:
public function edit()/*this is controller */
{
$data=array('column_name'=>$this->input->post('checkboxes');
$result=$this->estate_m->InsertCheckbox($data);
if($result==true)
{
echo "Success";
}
else
{
echo "Fail";
}
}
public function InsertCheckbox($data) /*this is Model */
{
$this->db->insert('property_type_details', $data);
return ($this->db->affected_rows() != 1 ) ? false : true;
}
With this edited code always gives me Succes

Form submitted values should be in multi dimension array
To achieve that your form inputs should be in multi dimension.
For insert_batch() function, the array should be in multi dimension.
In array every key must be field names in db table and value must be the form input value.
So change the form structure like the below array.
array(
array(
'checkboxes' => 'checkboxe value' ,
'cena' => 'cena values'
),
array(
'checkboxes' => 'checkboxe value' ,
'cena' => 'cena values'
)
);
Form inputs should be like below:
<input name="data[1][checkbox_columnname]" type="checkbox" value="21">Пентхаус
<input name="data[1][textbox_columnname]" type="text">
<input name="data[2][checkbox_columnname]" type="checkbox" value="22">Гараж/Паркомясто
<input name="data[2][textbox_columnname]" type="text">
And the model should not have foreach loop.
Simply pass the data as below.
$data=$this->input->post('data');
$this->db->insert_batch('mytable', $data);

Please use this code in model.
public function InsertCheckbox() {
$property_typesRequest = $this->input->post('checkboxes');
foreach($property_typesRequest as $value){
$data['columnename'] = $value;
$this->db->insert('tablename', $data);
}
}
Hope it inserts into the database
Thank you

Related

How to store multiple checkbox values to database in Laravel?

I need to store checkbox values into the database. I have tried so many examples, but still am not able to do that, Here I will give you my code and give me the solution for this.
My Blade File
<div class="form-group row">
<label for="hobbies" class="col-md-4 col-form-label text-md-right">Hobbies</label>
<div class="col-md-6">
<input type="checkbox" name="hobbies[]" value="Readbooks"/> Readbooks
<input type="checkbox" name="hobbies[]" value="Games"/> Games
<input type="checkbox" name="hobbies[]" value="Music"/> Music
#if ($errors->has('hobbies'))
<span class="text-danger">{{ $errors->first('hobbies') }}</span>
#endif
</div>
</div>
My Controller File
public function postRegistration(Request $request)
{
$data = $request->all();
$check = $this->create($data);
return redirect("login")->withSuccess('Great! please login.');
}
public function create(array $data)
{
return User::create([
'hobbies' => $data->implode([',', (array) $data->get('hobbies')]),
]);
}
Error:Call to a member function implode() on array
This is not how you use the implode method. And like the error says; you try to call a method on an array, because $data is an array and not an object.
And last, $data->get('hobbies') will also cause you problems, because the get() helper is not working on an array.
This is what you need:
return User::create([
'hobbies' => implode(',', (array) $data['hobbies']),
]);
When you have inputs like:
<input type="checkbox" name="hobbies[]" value="Readbooks"/> Readbooks
<input type="checkbox" name="hobbies[]" value="Games"/> Games
<input type="checkbox" name="hobbies[]" value="Music"/> Music
The POST data received by the server includes hobbies as an array. You can confirm this by inspecting the received request in your controller:
public function postRegistration(Request $request) {
dd($request);
}
Since $request->hobbies is already an array, there is no need to cast it with (array).
In the code you've shown, you are trying to implode() your hobbies. implode() generates a string, so if the hobbies field you are trying to populate in the database is a string, you simply need to implode that received array of hobbies:
// Will generate a string like: "Readbooks,Music"
implode(',', $request->hobbies);
Putting it into your code:
public function create($data) {
return User::create(['hobbies' => implode(',', $data->hobbies)];
}

How sort json array result in codeigniter 4

if mind, anyone can tell me how to sort by created_at on json array.
I want the newest comment on top, not on the bottom.
Here is my code :
Model (to insert and get comment data):
public function add_komen($data){
return $this->komen->insert($data);
}
public function get_komen($id){
return $this->komen->where('id_user', $id)->get()->getResultArray();
}
Controller (get data & get result using array for views):
public function do_add_komentar(){
$data['nama_komentar'] = $this->request->getPost('nama');
$data['isi_komentar'] = $this->request->getPost('komentar');
$data['id_user'] = $_SESSION['id_user'];
$update = $this->UndanganModel->add_komen($data);
if($update){
echo json_encode(array('status' => 'sukses','nama' => \esc($data['nama_komentar']),'komentar' => \esc($data['isi_komentar']) ));
}else{
echo json_encode(array('status' => 'gagal'));
}
}
Views (Form & Get Result):
<input id="nama" type="text" class="form-control mt-2" placeholder="Nama Anda" required>
<textarea id="komentar" class="form-control" id="exampleFormControlTextarea1" placeholder="Pesan anda.." rows="3" required></textarea>
<button id="submitKomen" class="btn btn-primary btn-block" >Kirim</button>
<div class="layout-komen">
<?php foreach($komen as $key => $data) { ?>
<div class="komen" >
<div class="col-12 komen-nama">
<?= \esc($data['nama_komentar']); ?>
</div>
<div class="col-12 komen-isi">
<?= \esc($data['isi_komentar']); ?>
</div>
</div>
<?php } ?>
</div>
You have no need to sort json array. This can be achieved simply by sorting for created_at in your model function for get result. I am assuming that created_at is column name in your table. if not then replace created_at with the column name. See code here
public function get_komen($id){
return $this->komen->where('id_user', $id)->orderBy("created_at", "desc")->get()->getResultArray();
}
check and reply

Trying to pass a value to a model using Codeigniter

Trying to learn Coedigniter here and struggling a little bit from the start. I basically want to create a query in my model using a value in the url.
Controller (Customer.php)
public function customer_edit($id) {
$this->load->model( 'Customers_model' ); //loads model
$data[ 'results' ] = $this->Customers_model->edit_customers($id);
$this->load->view( 'customers/customer_edit', $data );
}
Model (customers_model.php)
public function edit_customers($id)//This function returns an array
{
$this->load->database('default', TRUE); //connect to database
$this->db->where(['idcustomers'=>$id]); //creates where statement from url
$query = $this->db->get('customers');//create query
return $query->result_array(); //creates array from query
}
View (customer_edit.php)
<div class="form-group">
<label class="control-label col-sm-2">First Name:</label>
<div class="col-sm-3"><input type="text" class="form-control" name="txtfname" value="<?php echo $results['fname'];?>">
</div>
<label class="control-label col-sm-2">Last Name:</label>
<div class="col-sm-3"><input type="text" class="form-control" name="txtlname" value="">
</div>
</div>
When I go to http://blahblah.com/customers/customer_edit/454 I get the following error:
Message: Undefined index: fname
Filename: customers/customer_edit.php
Line Number: 10
This is what I know:
On other pages where I am just displaying all the records in a table it works fine so I am not having a database connection problem. fname and idcustomers are the correct column names in the database.
Thanks in advance for your help.
Here is how I solved the problem. I added a foreach at the beginning of the form like this:
<div class="form-group">
<label class="control-label col-sm-2">First Name:</label>
<div class="col-sm-3"><input type="text" class="form-control" name="txtfname" value="<?php echo ucwords(strtolower($object['fname']));?>">
</div>
Thanks Ghost for helping answer this question.

dropdown select value in yii

I am currently trying to create a sample shopping site,The problem came when I created a search page.In my search page I Have two fields one for enter the keyword and other for select type of item
Which means search,keyword in the selected item.but the item defined in DB is 0 and 1 and i Trying to get it my code but fails...could any one help me...
The Gfunction code is
public static function item(){
$optionList='';
$CategoryList = OfferEvents::model()->findAllByAttributes(array());
foreach($CategoryList as $catdata)
{ $optionList.="<option value='".$catdata['type']."'>".$catdata['name']."</option>"; }
return $optionList;
}
and view code is
<form action="<?php echo Yii::app()->baseUrl; ?>/offer?>" method="GET" class="form-inline form-section-2 row fadeInDown animated">
<div class="col-sm-5 form-group">
<input type="text" name="search" class="form-control" id="search" value="" placeholder="Enter Your Keyword">
</div>
<div class="col-sm-4 form-group">
<select name="cat" class="form-control selectpicker">
<option value='0'>Select type</option>
<?php echo GFunctions::item(); ?>
</select>
</div>
<div class="col-sm-3 form-group">
<button type="submit" class="btn btn-default btn-new">Search</button>
</div>
</form>
why don't you use Yii built in functions to handle the dropdown?
I am not sure how your Models looks like but you can choose one of the following functions to achieve what you want instead of trying to return a String $optionList with HTML tags.
CHtml::activeDropDownList() // for directly bind to active record model
CHtml::dropDownList()
Try this code....
Function
public static function item(){
$CategoryList = OfferEvents::model()->findAllByAttributes(array());
$optionList = CHtml::listData($countries, 'type', 'name')
return $optionList;
}
In view
<?php echo CHtml::dropDownList('cat', '', GFunctions::item(), array('prompt'=>'Select type'));?>

CodeIgniter: Populate an input text in the view from data array grabbed from database

This return of print_r($query->result()); would be:
Array ( [0] => stdClass Object ( [guest_name] => Test Name [guest_gender] => Male [guest_nic_pp_dl] => 123456789 ) )
What I need is to pass those values into input text boxes, radio buttons and dropdowns in the view respectilvely.
For example, I need 'guest_name' to be in an input, 'guest_gender' value to be selected on the view, and dropdown value corresponding to 'guest_nic_pp_dl' to be selected on a dropdown (HTML select).
Controller:
function get_customer_details() {
$guest_name = $this->input->post('guest_name');
$this->banquet_model->talk_to_new_guest_table($guest_name);
$this->load->view('/main/banquet_view');
}
Model:
function talk_to_new_guest_table($guest_name) {
$query = $this->db->query(" SELECT guest_name, guest_gender, guest_nic_pp_dl
FROM new_guest
WHERE guest_name LIKE '$guest_name%'
LIMIT 1 ");
if($query->num_rows()>0) {
return $query->result();
}
else {
return 0;
}
}
View:
<div class="control-group">
<label for="guest_name" class="control-label"><i class="icon-user"></i> Name: </label>
<div class="controls">
<div class="input-append">
<input type="text" id="appendedInputButtons" class="span2" name="guest_name" value="<?php echo set_value('guest_name'); ?>">
<input class="btn" type="submit" name="searchGuest" value="Search">
</div>
<?php echo form_error('guest_name'); ?>
</div>
make some changes in
Controller :
$guest=$this->banquet_model->talk_to_new_guest_table($guest_name);
//creating data array from returned result
$data['guest_name']=$guest->guest_name;
$data['guest_gender']=$guest->guest_gender;
$data['guest_nic_pp_dl']=$guest->guest_nic_pp_dl;
//loading view with data
$this->load->view('/main/banquet_view',$data);
more important all these data array element will be available as variable on view page like
$data['guest_gender'] as $guest_gender
The answers from Rajeev Ranjan and Prasanth are ok but on the line return $query->result(); you can do thisreturn $query->row(); the reason is because the result() returns an array of objects which needs to be iterated while the row() object returns a single object which you can reference without iterating with a loop. I hope this will help
Try something on the lines of:
Controller:
function get_customer_details() {
$guest_name = $this->input->post('guest_name');
$data = $this->banquet_model->talk_to_new_guest_table($guest_name);
if ($data != 0) {
$this->load->view('/main/banquet_view', $data);
}
}
Model:
function talk_to_new_guest_table($guest_name) {
$query = $this->db->query(" SELECT guest_name, guest_gender, guest_nic_pp_dl
FROM new_guest
WHERE guest_name LIKE '$guest_name%'
LIMIT 1 ");
if($query->num_rows()>0) {
return $query->result();
}
else {
return 0;
}
}
View:
<div class="control-group">
<label for="guest_name" class="control-label"><i class="icon-user"></i> Name: </label>
<div class="controls">
<div class="input-append">
<input type="text" id="appendedInputButtons" class="span2" name="guest_name" value="<?php echo $guest_name; ?>">
<input class="btn" type="submit" name="searchGuest" value="Search">
</div>
<?php echo form_error('guest_name'); ?>
</div>

Categories