In this tutorial, we will learn to convert CodeIgniter query to json and also to insert them in our database.

It is difficult to store an array in database which contains a lots of user data. We will have to make a lots of indexes in array in order to store them in database.

In such situation, json is very helpful. Using json function we can convert array values into json string and store them easily in database.

Whenever we need the data, we can again convert  json data back into array.

Syntax :

json_encode();     // Convert array into json string
json_decode();     // Convert json string back to array

You can also refer our live demo or download the Script file. Extract the downloaded files, save it in your local server and run it using given path 

codeigniter insert json data on db


Logic Behind json encode and decode

Encode array to json using  json_encode()

<?php
// This is a simple array
$var1 = array(
'key_name1' => 'value_name1',
'key_name2' => 'value_name2'
);

//We are converting array in encode $var1 array to json using json encode
$encode_data = json_encode($var1);
echo $encode_data;
?>

Result: Array Converted to JSON

{"key_name":"value_name","key_name1":"value_name1"} 

Decode json to array using  json_decode()

<?php
// This is a simple array, We are converting array in
$var1 = array(
'key_name1' => 'value_name1',
'key_name2' => 'value_name2'
);

//encode $var1 array to json using json_encode()
$encode_data = json_encode($var1);
echo $encode_data;

//decode json data($encode_data) to array, using json_decode()
$decode_data = json_decode($encode_data);
print_r($decode_data);
?>

Result: JSON Converted to Array(stdClass Object)

stdClass Object ( [key_name1] => value_name1 [key_name2] => value_name2 )

Extract data from stdClass Object

By forech

<?php
foreach ($decode_data as $value){
echo $value."<br>";
}?>

Output :

value_name1
value_name2

Fetch data from object

<?php

echo $decode_data->key_name1;
echo "<br>";
echo $decode_data->key_name2;

?>

Output :

value_name1
value_name2

Tutorial Scripts in detail

Below are the details of the code used in this tutorial with proper explanation.

First of all create a database name employee and table name employee_info as given below.

CREATE DATABASE employee;
CREATE TABLE employee_info(
 `emp_id` int(11) NOT NULL AUTO_INCREMENT,
`emp_data` varchar(255) NOT NULL,
PRIMARY KEY (`emp_id`)
)

Now, open application/config/database.php and make entry of database as given below.

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'employee';
$db['default']['dbdriver'] = 'mysql';

Also, open application/config/autoload.php and load database library  and helper library as given below.

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url','file','form');

All required library and helpers are loaded. Now, create controllers, views and model as given below,

Controllers : form.php

Form controller fetch users submitted data, store them in an array and convert array into json string.

Created json string then send to database where it is stored.

<?php

class Form extends CI_Controller {

public function __construct() {
parent::__construct();
$this->load->model("json_model");
}

// Load view page
public function index() {
$this->load->view("view_form");
}

// Fetch user data and convert data into json
public function data_submitted() {

// Store user submitted data in array
$data = array(
'employee_name' => $this->input->post('emp_name'),
'employee_email' => $this->input->post('emp_email'),
'employee_gender' => $this->input->post('select'),
'employee_address' => $this->input->post('address'),
);

// Converting $data in json
$json_data['emp_data'] = json_encode($data);

// Send json encoded data to model
$return = $this->json_model->insert_json_in_db($json_data);
if ($return == true) {
$data['result_msg'] = 'Json data successfully inserted into database !';
} else {
$data['result_msg'] = 'Please configure your database correctly';
}

// Load view to show message
$this->load->view("view_form", $data);
}

}

?>

Views : view_form.php

It shows the form page where user can enter and submit employee data.

<html>
<head>
<title>Codeigniter Json</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="main">
<div id="content">
<h2 id="form_head">Convert CodeIgniter Query to Json & Insert Into Database</h2>
<div id="form_input">
<?php
echo form_open('form/data_submitted');
echo form_label('Employee Name' . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
$data_name = array(
'name' => 'emp_name',
'id' => 'emp_name_id',
'class' => 'input_box',
'placeholder' => 'Please Enter Name',
'required' => 'required'
);
echo form_input($data_name);
echo form_label('Employee Email-ID');
$data_email = array(
'type' => 'email',
'name' => 'emp_email',
'id' => 'e_email_id',
'class' => 'input_box',
'placeholder' => 'Please Enter Email',
'required' => 'required'
);
echo form_input($data_email);
echo form_label('Gender');
$data_gender = array(
'Male' => 'Male',
'Female' => 'Female'
);
echo form_dropdown('select', $data_gender, 'Male', 'class="dropdown_box"');
echo form_label('Address');
echo "<div class='textarea_input'>";
$data_textarea = array(
'name' => 'address',
'rows' => 5,
'cols' => 28,
'placeholder' => 'Address...',
'required' => 'required'
);
echo form_textarea($data_textarea);
echo "</div>";
?>
</div>
<div id="form_button">
<?php echo form_submit('submit', 'Submit', "class='submit'"); ?>
</div>
<?php echo form_close(); ?>
</div>
</div>
<?php
if (isset($result_msg)) {
echo "<div id='res_msg'>";
echo $result_msg;
echo "</div>";
}
?>
</body>
</html>

Models : json_model.php

Json_model interact with database and stored json string into database.

Note : if you want decode json data, just retrieve data from database and use json_decode();  to convert json string into array.

<?php

class Json_Model extends CI_Model {

// Insert json data into database
public function insert_json_in_db($json_data) {
$this->db->insert('employee_info', $json_data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}

}

?>

CSS : style.css

Styling HTML Elements.

body {
font-family: 'Raleway', sans-serif;
}
.main{
width: 1015px;
position: absolute;
top: 10%;
left: 20%;
}
#form_head{
text-align: center;
background-color: #FEFFED;
height: 66px;
margin: 0 0 -29px 0;
padding-top: 35px;
padding-bottom: 22px;
border-radius: 8px 8px 0 0;
color: rgb(97, 94, 94);
}
#content {
width: 481px;
height: auto;
border: 2px solid gray;
border-radius: 10px;
margin-top: -40px;
margin-left: -60px;
}
#form_input{
font-size: 16px;
font-family: 'Raleway', sans-serif;
margin-left: 50px;
margin-top: 36px;
}
label{
margin-right: 6px;
}
#form_button{
padding: 0 21px 15px 15px;
bottom: 0px;
width: 445px;
background-color: #FEFFED;
border-radius: 0px 0px 8px 8px;
border-top: 1px solid #9A9A9A;
}
.submit{
font-size: 16px;
font-family: 'Raleway', sans-serif;
background: linear-gradient(#ffbc00 5%, #ffdd7f 100%);
border: 1px solid #e5a900;
color: #4E4D4B;
font-weight: bold;
cursor: pointer;
width: 300px;
border-radius: 5px;
padding: 10px 0;
outline: none;
margin-top: 20px;
margin-left: 15%;
}
.submit:hover{
background: linear-gradient(#ffdd7f 5%, #ffbc00 100%);
}
.label_output{
color:#4A85AB;
margin-left: 10px;
}
.dropdown_box{
font-size: 16px;
font-family: 'Raleway', sans-serif;
height:40px;
width:240px;
border-radius:3px;
background-color:#FEFFED;
}
.input_box{
font-size: 16px;
font-family: 'Raleway', sans-serif;
height:40px;
width:240px;
padding:5px;
border-radius:3px;
border: 1px solid #A9A9A9;
background-color:#FEFFED;
}
.textarea_input{
margin-left: 145px;
margin-top: -16px;
}
textarea{
font-family: 'Raleway', sans-serif;
font-size: 16px;
padding:5px;
background-color:#FEFFED;
}
.address_div{
width: 50px;
height:auto;
}
#res_msg{
font-family: 'Raleway', sans-serif;
font-size: 16px;
position: absolute;
top: 610px;
left: 328px;
color: blue;
}

Conclusion:

In this way, we can Convert CodeIgniter Query to Json & Insert Into Database. Hope you might have understood it properly, keep reading our other blogs posts for more coding tricks.