且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数组值转换为字符串并保存到数据库

更新时间:2023-11-15 16:35:13

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 .