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
Related
I save my data like this
public function saveInvestors($id = 0)
{
$data = array ('id' => $id );
$data2 = array ('ref_id' => $data['id]);
if ($id == 0)
{
return [$this->db->insert('investor', $data), $this->db->insert('leveling', $data2)];
}
}
my id on $data is auto increment on database while id on $data2 is not my problem here is that I couldn't get the id on $data and insert it on leveling but it always returning 0
You need to get the inserted id after inserting it into the database:
$this->db->insert('investor', $data);
$new_id = $this->db->insert_id();
As seen in the documentation: https://codeigniter.com/user_guide/database/helpers.html
Try this.
public function saveInvestors($id = 0)
{
$data = array('id' => $id);
if ($id == 0) {
$this->db->trans_begin();
$this->db->insert('investor', $data);
$id_investor = $this->db->insert_id();
$data2 = array('ref_id' => $id_investor);
$this->db->insert('leveling', $data2);
if ($this->db->trans_status() === TRUE) {
$this->db->trans_commit();
return TRUE;
} else {
$this->db->trans_rollback();
return FALSE;
}
}
}
I am trying to fetch data from database in code-igniter .Bur this loop return only one loop .
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
You need to define $userdatas=array(); outside the loop. It is inside the loop that's why it overrides the data and returns the last record.
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
$userdatas = array();
foreach($userchatData as $key => $userdata){
$userdatas[]= array(
'chat_id' => $userdata['chat_id'],
'chat_from' => $userdata['chat_from'],
'created_date' => $userdata['created_date']
);
}
$data['ChatdatabyId'] =$userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
echo json_encode($data);
Hope this will help you :
$userchatData = $this->db->get($this->db->dbprefix('usres_chat'))->result_array();
foreach($userchatData as $key => $userdata)
{
$userdatas[$key]['chat_id'] = $userdata['chat_id'];
$userdatas[$key]['chat_from'] = $userdata['chat_from'];
$userdatas[$key]['created_date'] = $userdata['created_date'];
}
/*print_r($userdatas); output here*/
$data['ChatdatabyId'] = $userdatas;
$data['responseCode'] = '200';
$data['responseMessage'] = 'User listing successfully';
}
echo json_encode($data);
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
I see that one can use an array with Jtable load, I tried the following:
public function delete($id = null) {
$app = JFactory::getApplication();
$id = $id ? $id : $app->input->get('files', array(), 'ARRAY');
$file = JTable::getInstance('Document','Table');
$file->load($id);
$file->date_removed = date("Y-m-d H:i:s",time());
if($file->store())
{
return true;
} else {
return false;
}
}
print_r($id) is:
Array
(
[0] => 1
[1] => 2
)
But I am having no luck. I keep getting the following error:
0 - Missing field in database: TableDocument 1.
Documentation on JTable
Any Help Greatly Appreciated.
Well actually you doing it wrong. You can load JTable with few field values, but it only returns 1 result;
Example use:
$data = array('id' => 100, 'user_id' => 101);
$table->load($data);
The code above will search for table entry with id = 100 AND user_id = 101. You cannot load 2 table entries like that.
My suggestion would be:
public function delete($id = null) {
$ids = array();
$return = true;
if ($id) {
$ids[] = $id;
} else {
$ids = JFactory::getApplication()->input->get('files', array(), 'ARRAY');
}
if (count($ids) > 0) {
foreach ($ids as $id) {
$file = JTable::getInstance('Document','Table');
$file->load($id);
$file->date_removed = date("Y-m-d H:i:s",time());
$temp = $file->store();
$return = $return || $temp;
}
}
return $return;
}
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()));