cakephp getting value of textfield in model - php

Hi I have dynamically added input fields on my add view. When I submit my form I want all them input fields to be concatenated into one string and stored in a single database field.
Im trying to achieve this using the beforeSave method of cakephp but I can't seem to find out how to get the values of a text field within the Model.
function beforeSave($options)
{
$result = '';
$bool = true;
$counter = 0;
while($bool == true)
{
$result = $result + ',' + $this->data['Variable']['selectOptions' + counter];
}
return true;
}
Anyone any ideas on how to achieve this?
Thanks in advance.

In my opinion (from MVC point of view) it would be better to concatenate the fields in controller and then unset unnecessary fields before saving the model...

after get the post values in model you can merge the array values into a single variable like this..
<?php
$var = array('test1','test2','test3','test4','test5','test6');
$new_values = implode(',',$var);
echo $new_values;
?>
You can retrieve these values after saving to database.

this might not be the perfect answer but might give you some head start in that direction
function beforeSave($options = array()) {
pr($this->data); // <= show data you intend to save
exit;
}
use foreach to loop the data array ($this->data) and perform concatenation on the values and assign the concatenated string to the feild name
function beforeSave($options = array()) {
foreach ($this->data['Variable'] as $key=>$value)
{
$feildflag = strstr($key, 'selectOptions');
if($feildflag){
$concatenatedstring .= $value;
}
}
$this->data['Variable']['your_feild_name'] = $concatenatedstring ;
}

Your dynamic form field should looks like in a foreach loop:
<?php echo $this->Form->input('Model.field][', array());
In your model:
function beforeSave($options)
{
if(!empty($this->data))
{
$this->data['Model']['common_field'] = implode(",", $this->data['Model'['field'];
unset($this->data['Model']['field']);
}
}

Related

Codeigniter Database Error Number 1048 Values show NULL even though they are NOT NULL

I have situation where codeigniter shows database Error Number 1048. It seems Values NULL but when I try to check it usign var_dump($_POST) Values are not NULL.
Controller : Jurusan.php
public function simpan()
{
$this->form_validation->set_rules('code','Kode','required|integer');
$this->form_validation->set_rules('jurusan','Jurusan','required');
$this->form_validation->set_rules('singkatan','Singkatan','required');
$this->form_validation->set_rules('ketua','Ketua','required');
$this->form_validation->set_rules('nik','NIK','required|integer');
$this->form_validation->set_rules('akreditasi','Akreditasi','required');
if($this->form_validation->run() == FALSE)
{
$isi['content'] = 'jurusan/form_tambahjurusan';
$isi['judul'] = 'Master';
$isi['sub_judul'] = 'Tambah Jurusan';
$this->load->view('tampilan_home',$isi);
} else {
$this->model_security->getSecurity();
$key = $this->input->post('code');
$data['kd_prodi'] = $this->input->post['code'];
$data['prodi'] = $this->input->post['jurusan'];
$data['singkat'] = $this->input->post['singkatan'];
$data['ketua_prodi'] = $this->input->post['ketua'];
$data['nik'] = $this->input->post['nik'];
$data['akreditasi'] = $this->input->post['akreditasi'];
$this->load->model('model_jurusan');
$query = $this->model_jurusan->getdata($key);
if($query->num_rows()>0)
{
$this->model_jurusan->getupdate($key,$data);
} else {
$this->model_jurusan->getinsert($data);
}
redirect('jurusan');
}
}
Model : model_jurusan.php
class Model_jurusan extends CI_model {
public function getdata($key)
{
$this->db->where('kd_prodi',$key);
$hasil = $this->db->get('prodi');
return $hasil;
}
public function getupdate($key,$data)
{
$this->db->where('kd_prodi',$key);
$this->db->update('prodi',$data);
}
public function getinsert($data)
{
$this->db->insert('prodi',$data);
}
}
Here is the error shown :
Here is the database structure :
You have a wrong syntax in these lines:
$key = $this->input->post('code');
$data['kd_prodi'] = $this->input->post['code']; // <-- use ('code')
$data['prodi'] = $this->input->post['jurusan']; // <-- use ('jurusan')
Change this to
$this->input->post['array_key'];
this
$this->input->post('array_key');
Read : Input Class in Codeigniter
Well the problem lies in your way of accepting input parameters.
$this->input->post
is a method which accepts the variable name, not an array. So all the input parameters need to be passed as a function parameter to post method. These lines need to be altered to.
$data['kd_prodi'] = $this->input->post('code');
$data['prodi'] = $this->input->post('jurusan');
$data['singkat'] = $this->input->post('singkatan');
$data['ketua_prodi'] = $this->input->post('ketua');
$data['nik'] = $this->input->post('nik');
$data['akreditasi'] = $this->input->post('akreditasi');
Hope this solves the problem.
EDIT:
You did a var_dump($_POST) which works as it is supposed to and it will read the values of the post parameters. So either you fetch the parameters from $_POST array, or you use the $this->input->post() method. But I would suggest using the $this->input->post() method as it provides additional sanitization such as xss attack handling etc, which could be turned on an off from the config.
i have tried your code...it works. I think there some mistakes in your <input> tags, You must use <input name=""> not <input id=""> or something else. Hope it can help you out
You are try to get value from post is wrong. You should use at this way
$_POST['array value'];

how to insert array data in single column in mysql using codeigniter

I'm trying to insert array data into database using codeigniter. when I print that values using print_r() fun.
It shows correct result, but when I click on save button it inserts blank values in table.
I just want to store multiple medicine names in prescription table for particular prescription_id i am trying to insert data using insert_batch function but it saves blank records
this is my model code:
public function add_prescription($data) {
$data['medicine_name'] = $data['medicine_nm[]'];
print_r($data['medicine_name']);
$this->db->insert_batch('pre',$data);
return $this->db->insert_id($pre_id);
}
controller code--
public function prescription($patient_id = NULL, $app_date = NULL, $hour = NULL , $min = NULL) {
//Check if user has logged in
if (!$this->session->userdata('user_name') || $this->session->userdata('user_name') == '') {
redirect('login/index/');
} else {
if ($this->form_validation->run() === FALSE) {
$data['medicine_nm[]']=$this->input->post('medicine_nm[]');
$this->patient_model->add_prescription($data);
}
}
}
You need to json_encode that array and then insert it into the database like
$data = json_encode($array);
$this->db->insert('column_name',$data);
And while fetching you need to decode it
$data = json_decode($column_result);
Hope this helps you.
try this
public function add_prescription($name) {
$data = array(
'medicine_name' => $name
);
$query = $this->db->insert('table_name',$data);
return $query->result_array();
}
Hope this will help you

How to search for multiple values in a single field of mysql table using codeigniter active record?

I have to search for multiple values in a field using mysql in codeigniter. Here follows my code.
In Controller
public function vpsearch()
{
$data['info'] = $this->psearch_m->emp_search_form();
$this->load->view("employer/result",$data);
}
IN Model
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
$jrole = $this->input->post('ps_jobrole'));
if ( $jrole !== NULL)
{
return $this->db->get('js_edu_details');
$this->db->like('js_skills','$skill');
}
}
In view i.e, (../employer/result)
foreach($info->result() as $row)
{
echo $row->js_id."<br/><br/>" ;
}
However I am getting all the records in 'js_edu_details' table instead of fields having searched 'skills'.
Where I am going wrong? Any help wud b appreciated, thanx in advance.
Try:
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
//$skill = $this->input->post('ps_skills', true); other short way of getting the above result with `xss clean`
if ( $jrole !== NULL)
{
$this->db->like('js_skills',$skill); #remove the single quote around the `$skill`
$res = $this->db->get('js_edu_details');
echo $this->db->last_query(); #try to print the query generated
return $res;
}
}
Return statement should be after the like statement
You should arrange the code properly like this
public function emp_search_form()
{
$ps_skills = $this->input->post('ps_skills')
$skill = $this->security->xss_clean($ps_skills);
if ( $jrole !== NULL)
{
$this->db->like('js_skills','$skill');
return $this->db->get('js_edu_details');
}
}
Also you should note the condition will never meet. It will always give error undefined variable $jrole

Form validation for multiple text input Codeigniter

Array values in form are always a problem for form validation in CI. Now I've to input multiple values and those array values are to be stored in DB. Now the user can keep some fields blanks by mistake as shown below in the links:
Input values.
Values in the array on submission.
I used this tutorial to add input boxes on + button click. On submission the blank values will be truncated and then not null array values will added to database. I tried this using a sample program in native PHP but could not implement it in CI.
I used the following code in native PHP to insert values in DB truncating null values:
<?php
include 'sql_connect.php';
$str = array();
for($i=0;$i<count($_POST["txtSiteName"]);$i++)
{
$str[] = $_POST["txtSiteName"][$i];
}
$str = array_filter($str, function($item) {if(!is_null($item)) return $item;});
foreach($str as $loop_str)
{
$arr_str[] = $loop_str;
}
for($k = 0; $k<count($arr_str);$k++)
{
mysql_query("INSERT INTO sitename (name) VALUES ('".$arr_str[$k]."')") or die(mysql_error());
}
print_r($arr_str);
?>
How can I achieve this in CI ?
I tried to use callback function but the array value is not being passed to the callback function.
EDIT:
The below code shows my callback function :
On entering 3 urls it is called 3 times. Is that normal ?
Also my array_walk's callback function is not working. Calling a callback function inside another callback function is not possible ?
public function null_check()
{
$urls = $this->input->post('link_name');
array_walk($urls, 'prepurl');
var_dump($urls);
}
prepurl function:
public function prepurl($item, $key)
{
$item = "http://".$item;
}
Your question is not clear to me but since you mentioned to validate multiple text boxes. So if your text boxes are something like this
<input type="text" name="txtSiteName[]" />
<input type="text" name="txtSiteName[]" />
then simply you can use
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'required|xss_clean');
to validate all the text boxes against null or empty.
Update (TO pass an argument in to the callback)
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'callback_sitename_check[' . $this->input->post('txtSiteName') . ']');
function sitename_check($str, $sitenames) {
// $sitenames will be your textboxe's array
}
The first argument is used by CodeIgniter by default so second argument is your parameter. Also take a look at insert_batch() to insert multiple records.
Also you can do this like
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'callback_sitename_check');
function sitename_check() {
$sitenames = $this->input->post('txtSiteName');
}
Update: (For array_walk)
array_walk($urls, array($this, 'prepurl'));
Here is a simple process of doing it
Set message like this
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'required|xss_clean|callback_check_array');
Here is callback
function check_array()
{
$txtSiteName = $this->input->post('txtSiteName');
$error = 0;
foreach($txtSiteName as $key => $value)
{
if(!empty($value)){
$error = $error + 1;
}
}
if($error == 0){
return TRUE;
}else{
$this->form_validation->set_message('check_array', 'All fields are empty. Please provide at leaset 1');
return FALSE;
}
}
When validation is successfull run this code or modify according to your requirements
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$txtSiteName = $this->input->post('txtSiteName');
foreach($txtSiteName as $key => $value)
{
if(!empty($value)){
$data['name'] = $value;
$this->mymodel->insert($data);
}
}
}
Model Method
function insert($data)
{
$this-db->insert('table_name',$data);
}

How to get field names of mysql table in codeigniter?

i am new in codeigniter. And i am trying to get field name of a table with a query.
I have write a query
"select * from user"
and pass it to $this->db->query() function. i am getting records. But i want to get field names of table. so how can i get that?
Can anybody help me please. Thanks in advance.
using database library write this code to list all fields:
$this->db->list_fields('table')
take a look here: https://codeigniter.com/userguide3/database/results.html#CI_DB_result::list_fields
Some Times this may helpful
$fields = $this->db->field_data('table_name');
foreach ($fields as $field)
{
echo $field->name;
echo $field->type;
echo $field->max_length;
echo $field->primary_key;
}
What you did is to get the datas from the table....
here your table is user so
in your model function do this...
function get_field()
{
$result = $this->db->list_fields('user');
foreach($result as $field)
{
$data[] = $field;
return $data;
}
}
in your controller do this
function get_field()
{
$data['field'] = $this->model_name->get_field();
$this->load->view('view_name',$data);
}
in your view do this
foreach($field as $f)
{
echo $f."<br>"; //this will echo all your fields
}
hope this will help you
you can use the below code to fetch the field from db
$fields = $this->db->list_fields('table_name');
foreach ($fields as $field)
{
echo $field;
}
with the help of this code we can fetch the field names from db
include('db.php');
$col="SHOW COLUMNS FROM `camera details`";
$output=mysqli_query($db,$col);
$kal=array();
while($row=mysqli_fetch_array($output))
{
if($row['Field']!='id')
{
?><div class="values"><?php echo $row['Field'];
echo "<br>";?></div><br><br><?php
array_push($kal, $row['Field']);
}
}
?>
<?php**
The answer given above by Anwar needs modification, there is no need for foreach loop in model function as it will only give the first element despite using foreach, which means the foreach loop is not bringing the fields using $data[], below code should give you 100% result
in your model function do this...
function get_field()
{
$result = $this->db->list_fields('user');
return $result();
}
in your controller do this
function get_field()
{
$data['field'] = $this->model_name->get_field();
$this->load->view('view_name',$data);
}
in your view do this
foreach($field as $f)
{
echo $f."<br>"; //this will echo all your fields
}

Categories