how to convert array value to string and save to database - php

I have trouble, how to save array value in database, Each time I enter data only the last data stored in the database.
here is my code :
Controller :
function tambah_rm($id)
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Tambah Detail Rekam Medis';
$this->form_validation->set_rules('tgl_berobat', 'tgl_berobat', 'required');
$this->form_validation->set_rules('anamnesa', 'anamnesa', 'required');
$this->form_validation->set_rules('diagnosa', 'diagnosa', 'required');
$this->form_validation->set_rules('therapi', 'therapi', 'required');
$this->form_validation->set_rules('keterangan', 'keterangan', 'required');
if ($this->form_validation->run() === FALSE)
{
$data['obat']=$this->m_pasien->get_obat();
$data['header']=$this->m_pasien->header_pasien($id)->row_array();
$this->template->load('template','v_tambahRM',$data);
}
else
{
$this->m_pasien->tambahrm($data);
redirect('pasien');
}
}
My Model :
function tambahrm()
{
$this->load->helper('url');
$username = trim($this->session->userdata('id_user'));
$data = array(
'tgl_berobat' => $this->input->post('tgl_berobat'),
'anamnesa' => $this->input->post('anamnesa'),
'diagnosa' => $this->input->post('diagnosa'),
'therapi' => $this->input->post('therapi'),
'keterangan' => $this->input->post('keterangan'),
'id_user' => $username,
'id_pasien' => $this->input->post('id_pasien'),
);
if ($id == 0) {
return $this->db->insert('tbl_riwayat', $data);
} else {
$this->db->where('id', $id);
return $this->db->update('tbl_riwayat', $data);
}
}
function get_obat()
{
$data_obat = array();
$this->db->select('nama_obat');
$this->db->from('tbl_obat');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data_obat[] = $row;
}
}
return $data_obat;
}
View
<div class="form-group m-b-20">
<div class="col-xs-12">
<label for="therapi">Therapi</label>
<select class=" form-control js-example-basic-multiple" multiple="multiple" name="diagnosa">
<?php
foreach($obat as $option)
{
?>
<option value="<?=$option['nama_obat']?>"><?=$option['nama_obat']?></option>
<?php
}
?>
</select>
</div>
</div>
And this is a screenshoot of data stored in the database, which I put yellow color is the last data I input in multiple select field.

Php have multiple option to convert array into string some of the option you can try are listed below.
implode() /explode()
json_encode() / json_decode()
serialize() / unserialize()
Above answer telling you how to convert array into serialized . So i only mention other two option in my answer.
to convert the array into a string and back:
#Option one
function tambahrm()
{
$this->load->helper('url');
$username = trim($this->session->userdata('id_user'));
$data = array(
'tgl_berobat' => $this->input->post('tgl_berobat'),
'anamnesa' => $this->input->post('anamnesa'),
'diagnosa' => json_encode($this->input->post('diagnosa')),
'therapi' => $this->input->post('therapi'),
'keterangan' => $this->input->post('keterangan'),
'id_user' => $username,
'id_pasien' => $this->input->post('id_pasien'),
);
if ($id == 0) {
return $this->db->insert('tbl_riwayat', $data);
} else {
$this->db->where('id', $id);
return $this->db->update('tbl_riwayat', $data);
}
}
function get_obat()
{
$data_obat = array();
$this->db->select('nama_obat');
$this->db->from('tbl_obat');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$row['diagnosa'] = json_decode($row['diagnosa'],true);
$data_obat[] = $row;
}
}
return $data_obat;
}
#option two
function tambahrm()
{
$this->load->helper('url');
$username = trim($this->session->userdata('id_user'));
$data = array(
'tgl_berobat' => $this->input->post('tgl_berobat'),
'anamnesa' => $this->input->post('anamnesa'),
'diagnosa' => implode(",",$this->input->post('diagnosa')),
'therapi' => $this->input->post('therapi'),
'keterangan' => $this->input->post('keterangan'),
'id_user' => $username,
'id_pasien' => $this->input->post('id_pasien'),
);
if ($id == 0) {
return $this->db->insert('tbl_riwayat', $data);
} else {
$this->db->where('id', $id);
return $this->db->update('tbl_riwayat', $data);
}
}
function get_obat()
{
$data_obat = array();
$this->db->select('nama_obat');
$this->db->from('tbl_obat');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$row['diagnosa'] = explode(",",$row['diagnosa']);
$data_obat[] = $row;
}
}
return $data_obat;
}
First option using explode and implode and second option is using json_encode and decode.
you can use any option according to your requirement. But i personally suggest you json encode or serialized pick from this two as they do not change key index of any type of array .

You can use
json_encode() / json_decode()
serialize() / unserialize()
to convert the array into a serialized string and back:
function tambahrm()
{
$this->load->helper('url');
$username = trim($this->session->userdata('id_user'));
$data = array(
'tgl_berobat' => $this->input->post('tgl_berobat'),
'anamnesa' => $this->input->post('anamnesa'),
'diagnosa' => json_encode($this->input->post('diagnosa')),
'therapi' => $this->input->post('therapi'),
'keterangan' => $this->input->post('keterangan'),
'id_user' => $username,
'id_pasien' => $this->input->post('id_pasien'),
);
if ($id == 0) {
return $this->db->insert('tbl_riwayat', $data);
} else {
$this->db->where('id', $id);
return $this->db->update('tbl_riwayat', $data);
}
}
function get_obat()
{
$data_obat = array();
$this->db->select('nama_obat');
$this->db->from('tbl_obat');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$row['diagnosa'] = json_decode($row['diagnosa']) ?: null;
$data_obat[] = $row;
}
}
return $data_obat;
}
For reference, see:
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.serialize.php
http://php.net/manual/en/function.unserialize.php

Related

PHP CODEIGNITER UPDATE issue

I can't update data in a record in CodeIgniter .
I have posted the code below:-
//CONTROLLER
//RESERVATION.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reservation extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('reservation_model','reservation');
}
public function index()
{
$this->load->helper('url');
$this->load->view('manage_reservation');
}
public function reservationview()
{
$this->load->helper('url');
$this->load->view('view_reservation');
}
public function ajax_list()
{
$list = $this->reservation->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $reservation) {
$no++;
$row = array();
$row[] = $reservation->id;
$row[] = $reservation->dateReserved;
$row[] = $reservation->requestedBy;
$row[] = $reservation->facility;
$row[] = $reservation->dateFrom;
$row[] = $reservation->dateTo;
$row[] = $reservation->timeStart;
$row[] = $reservation->timeEnd;
$row[] = $reservation->status;
$row[] = $reservation->items;
$row[] = $reservation->purpose;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_reservation('."'".$reservation->id."'".')"><i class="glyphicon glyphicon-pencil"></i></a>
<a class="btn btn-sm btn-danger" href="javascript:void(0)" title="Hapus" onclick="delete_reservation('."'".$reservation->id."'".')"><i class="glyphicon glyphicon-trash"></i></a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->reservation->count_all(),
"recordsFiltered" => $this->reservation->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
public function ajax_edit($id)
{
$data = $this->reservation->get_by_id($id);
$data->dateFrom = ($data->dateFrom == '0000-00-00') ? '' : $data->dateFrom;
$data->dateTo = ($data->dateTo == '0000-00-00') ? '' : $data->dateTo; // if 0000-00-00 set tu empty for datepicker compatibility
echo json_encode($data);
}
public function ajax_add()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$insert = $this->reservation->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$this->reservation->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_delete($id)
{
$this->reservation->delete_by_id($id);
echo json_encode(array("status" => TRUE));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if($this->input->post('requestedBy') == '')
{
$data['inputerror'][] = 'requestedBy';
$data['error_string'][] = 'Requested Name is required*';
$data['status'] = FALSE;
}
if($this->input->post('dateFrom') == '')
{
$data['inputerror'][] = 'dateFrom';
$data['error_string'][] = 'Please Select a Date*';
$data['status'] = FALSE;
}
if($this->input->post('dateTo') == '')
{
$data['inputerror'][] = 'dateTo';
$data['error_string'][] = 'Please Select a Date*';
$data['status'] = FALSE;
}
if($this->input->post('timeStart') == '')
{
$data['inputerror'][] = 'timeStart';
$data['error_string'][] = 'Please select a Time*';
$data['status'] = FALSE;
}
if($this->input->post('timeEnd') == '')
{
$data['inputerror'][] = 'timeEnd';
$data['error_string'][] = 'Please select a Time*';
$data['status'] = FALSE;
}
if($this->input->post('status') == '')
{
$data['inputerror'][] = 'status';
$data['error_string'][] = 'Please Indicate Status*';
$data['status'] = FALSE;
}
if($this->input->post('items') == '')
{
$data['inputerror'][] = 'items';
$data['error_string'][] = 'Please select an Item*';
$data['status'] = FALSE;
}
if($this->input->post('purpose') == '')
{
$data['inputerror'][] = 'purpose';
$data['error_string'][] = 'Please indicate a Purpose*';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
}
//MODEL
//Reservation_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reservation_model extends CI_Model {
var $table = 'tblreservation';
var $column_order = array('id','dateReserved','requestedBy','facility','dateFrom','dateTo','timeStart','timeEnd','status','items','purpose',null); //set column field database for datatable orderable
var $column_search = array('id','dateReserved','requestedBy','facility','dateFrom','dateTo','timeStart','timeEnd','status','items','purpose'); //set column field database for datatable searchable just firstname , lastname , address are searchable
var $order = array('id' => 'desc'); // default order
public function __construct()
{
parent::__construct();
$this->load->database();
}
private function _get_datatables_query()
{
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else if(isset($this->order))
{
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
public function count_all()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('id',$id);
$query = $this->db->get();
return $query->row();
}
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
public function delete_by_id($id)
{
$this->db->where('id', $id);
$this->db->delete($this->table);
}
}
VIEW = manage_reservation.php = save function
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('reservation/ajax_add')?>";
} else {
url = "<?php echo site_url('reservation/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
NEWBIE TO CODE IGNITER any help will be appreciated :)
try
public function update($where, $data){
$this->db->where($where);
$this->db->set($data); //array of new data
$this->db->update($this->table);
return $this->db->affected_rows();
}
Please print your query after the update statement, this will help you to know whether you query is correct or not.
$this->db->last_query();
Please check that query in model
Controller :
$update_id = array();
$update_id['id'] = $this->input->post('id');
$data = array(
'id' => $this->input->post('id'),
'dateReserved' => $this->input->post('dateReserved'),
'requestedBy' => $this->input->post('requestedBy'),
'facility' => $this->input->post('facility'),
'dateFrom' => $this->input->post('dateFrom'),
'dateTo' => $this->input->post('dateTo'),
'timeStart' => $this->input->post('timeStart'),
'timeEnd' => $this->input->post('timeEnd'),
'status' => $this->input->post('status'),
'items' => $this->input->post('items'),
'purpose' => $this->input->post('purpose'),
);
$result = $this->reservation->update('table_name',$update_id, $data);
Model :
$this->db->where($where);
$this->db->update($table, $data);
return $this->db->affected_rows();

if no row found in table add button should be display else edit using codeigniter

in a row record found means edit button should be display or add button and no row found in a table it should be display add button,i am getting a problem while no row in table displaying edit but i want display add button please refer my below code.
Controller
$result = $this->Profile_model->buyer_details();
$data['c_address'] = $result->address;
$data['c_pincode'] = $result->pincode;
$data['c_district'] = $result->district;
$data['c_city'] = $result->city;
$data['c_state'] = $result->state;
$data['c_country'] = $result->country;
$this->load->view('buyerdetails', $data);
Model code
public function buyer_details() {
$this->db->select('*');
$this->db->from('customer_otherdetails');
$this->db->where('customerid_fk', $this->session->id);
$query = $this->db->get();
$rows = $query->result(); //so you only have to call result once
// $rows = $query->result_array();
if ($query->num_rows() > 0) {
foreach ($rows as $row) {
//add all data to session
$newdataa = array(
'address' => $row->address,
'pincode' => $row->pincode,
'city' => $row->city,
'district' => $row->district,
'state' => $row->state,
'country' => $row->country,
);
}
$this->session->set_userdata('buyer', $newdataa);
//put the return outside the if
//return $query->result();
}
// return $rows; //this will be an empty array if no data found
return $query->row();
}
view page
<a onclick="hideHasSub()" data-toggle="collapse" data-parent="#accordion" href="#collapseone">
<?php
if (empty($c_country) == $this->session->userdata('buyer')) {
?>
<span class="profile-edit">Add</span>
<?php } else { ?>
<span class="profile-edit">Edit</span>
<?php } ?>
</a>
$this->db->where('customerid_fk', $this->session->id);
here change
$this->db->where('customerid_fk', $this->session->userdata('id');
now your model ::
public function buyer_details() {
$this->db->select('*');
$this->db->from('customer_otherdetails');
$this->db->where('customerid_fk', $this->session->userdata('id');
$query = $this->db->get();
$rows = $query->result(); //so you only have to call result once
// $rows = $query->result_array();
if ($query->num_rows() > 0) {
foreach ($rows as $row) {
//add all data to session
$newdataa = array(
'address' => $row->address,
'pincode' => $row->pincode,
'city' => $row->city,
'district' => $row->district,
'state' => $row->state,
'country' => $row->country,
);
}
$this->session->set_userdata('buyer', $newdataa);
//put the return outside the if
//return $query->result();
}
// return $rows; //this will be an empty array if no data found
return $query->row();
}
Use this code in "a" tag
<?php
if (empty($c_country[0]) || empty($c_country)){?>
<span class="profile-edit">Add</span>
<?php } else { ?>
<span class="profile-edit">Edit</span>
<?php } ?>

Add or edit data if already exist in database

Im trying to add or edit data depending if its already stored in the database. As you can see below im checking if user already exist with getuserid($id) loading the corresponding view but the problem is when i trigger add_user() or edit_user() as none of these methods are redirecting back as it should be. Any suggestions? This is the complete code http://pastebin.com/2G7D8ie4
public function getuserid($id = NULL){
if(!$id)
{
show_404();
}
$query = $this->Users_model->getuserid($id);
if($query == false){
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/add_users_view',
'id'=>$id);
}else{
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/edit_users_view',
'id'=> $query->id,
'staff_id'=> $query->staff_id,
'login'=> $query->login,
'password'=> $query->password
);
}
$this->load->view('themes/'.$this->config->item('theme_front').'.php', $data);
}
Model
public function getuserid($id){
$query = $this->db->get_where('users', array('staff_id' => $id));
if($query->num_rows() > 0){
return $query->row();
}else{
return false;
}
}
can you try making your model
public function getuserid($id){
$query = $this->db->get_where('users', array('staff_id' => $id));
$result=array();
foreach ($query->result() as $rows){
$result[]=$rows;
}
return $result;
}
and controller
if(count($query)>0){
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/edit_users_view',
'id'=> $query->id,
'staff_id'=> $query->staff_id,
'login'=> $query->login,
'password'=> $query->password
);
}
else
{
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/add_users_view',
'id'=>$id
);
}

Combining Functions

How can put return tow function following in one function marge() and echo it with json_encode.
function get_gr()
{
//$tourf_id = $this->input->post('toname');
$id = '102';
$query = $this->db->order_by('id','desc')->get_where('table1', array('id' => $id));
if ($query->num_rows() == 0) {
return 0;
} else {
$query = $query->row();
return array('guide' => $query->guide);
}
}
function get_res()
{
//$id = $this->input->post('name');
$id = '102';
$data = array();
$query_r = $this->db->order_by('id','desc')->get_where('table2', array('relation' => $id));
if($query_r->num_rows() > 0){
foreach ($query_r->result() as $row) {
$data[] = array(
'name_re' => $row->name_re,
'id' => $row->id
);
}
return $hotel_data;
}else{
return 0;
}
}
function marge(){
echo json_encode(get_gr().get_res()); //This line 991
}
I get this erroe from above php code:
Fatal error: Call to undefined function get_gr() in D:\xampp\htdocsapplication\controllers\faile.php on line 991
What do i do?
If inside a controller, you must refer to get_gr() as $this->get_gr()
You can do a merge as two array elements.
echo json_encode(array(get_gr(), get_res()));

Codeigniter result array return only one row

Am trying to encode an array to json for use with jquery.
This is the function from my model
function get_latest_pheeds() {
$this->load->helper('date');
$time = time();
$q = $this->db->select("user_id,pheed_id,pheed,datetime,COUNT(pheed_comments.comment_id) as comments")
->from('pheeds')
->join('pheed_comments','pheed_comments.P_id=pheeds.pheed_id','left')
->group_by('pheed_id')
->order_by('datetime','desc')
->limit(30);
$rows = $q->get();
foreach($rows->result_array() as $row) {
$data['user_id'] = $row['user_id'];
$data['pheed_id'] = $row['pheed_id'];
$data['pheed'] = $row['pheed'];
$data['comments'] = $row['comments'];
$data['datetime'] = timespan($row['datetime'],$time);
}
return $data;
}
And this is from my controller
function latest_pheeds() {
if($this->isLogged() == true) {
$this->load->model('pheed_model');
$data = $this->pheed_model->get_latest_pheeds();
echo json_encode($data);
return false;
}
}
It returns only 1 row from the database when I run the code in the browser.
Please help me out
You are overwriting data in every iteration !!
Use something like
$data[] = array(
'user_id' => $row['user_id'];
'pheed_id' => $row['pheed_id'];
'pheed' => $row['pheed'];
'comments' => $row['comments'];
'datetime' => timespan($row['datetime'],$time);
) ;
This is good but your syntax should be 'user_id' => $row['user_id'], for each element of the array

Categories