How to post data as json in codeigniter? - json

I have to post data as json object format in codeigniter. how can it make possible.
My model function looks like:
public function signAction()
{
$name=$this->input->post('name',TRUE);
$dob=$this->input->post('dob',TRUE);
$gender=$this->input->post('gender',TRUE);
$country=$this->input->post('country',TRUE);
$city=$this->input->post('city',TRUE);
$mobile=$this->input->post('mobile',TRUE);
$email=$this->input->post('email',TRUE);
$password=$this->input->post('password',TRUE);
$this->db->select("*");
$this->db->where('email',$email);
$this->db->or_where('mobile',$mobile);
$query = $this->db->get('dr_signup');
$value=$query->num_rows();
if($value==0)
{
$sql = "INSERT INTO dr_signup (name,dob,gender,country,city,mobile,email,password)
VALUES(".$this->db->escape($name).",".$this->db->escape($dob).",".$this->db->escape($gender).",".$this->db->escape($country).",
".$this->db->escape($city).",".$this->db->escape($mobile).",".$this->db->escape($email).",".$this->db->escape($password).")";
$value1=$this->db->query($sql);
$insert_id = $this->db->insert_id();
$details = array(
'status'=>'success',
'message'=>'registered sucessfully',
'id' => $insert_id ,
'name' => $name,
'dob'=>$dob,
'gender'=>$gender,
'country'=>$country,
'city'=>$city,
'mobile'=>$mobile,
'email'=>$email,
);
echo json_encode($details);
}
else
{
$detail = array(
'status'=>'unsuccess',
'message'=>'already registered',
);
echo json_encode($detail);
}
}
I have to post the data as json format. My json objects looks like:
{"name":"jon","dob":"1jan2015","gender":"male","country":"India","city":"Mumbai","mobile":"86064 70000","email":"sales#green.tech","password":"1234"}
I am new to this. How can it make possible. what all modification should I have to do in code. thanking in advance.

say for example you get the json in $this->input->post('json_string',true); you can use the code like this..
$jsonstring = $this->input->post('json_string');
$json_data = json_decode($jsonstring,true); //remove true if you need object or keep it for array
The $json_data will give you the key value of the posted json string like $json_data['name'] ...

You try just like this
return json_encode($details);
delete your code "echo json_encode($details)"
I think it's working

Related

Is it possible to add some string before Column value in Laravel?

So, i need to put AWS S3 URL before the attachment value. I use Laravel Query builder to get data from database.
Query
$query = DB::table('subscriber')->select(['ID as SBC_ID','SUBSCRIBER_NAME','ATTACHMENT_OTHERS'])
->get();
return $query;
Result
[
{
"SBC_ID": 1,
"SUBSCRIBER_NAME": "NAME",
"ATTACHMENT_OTHERS": "uploads/1655362922-Annotation%202022-05-31%20141139.png"
},
{
"SBC_ID": 2,
"SUBSCRIBER_NAME": "NAME 2",
"ATTACHMENT_OTHERS": "uploads/1655362922-image.png"
}
]
The ATTACHMENT_OTHERS is from Form Request and uploaded to AWS S3. I just insert the attachment path, not full S3 URL. But now, i need to return full URL.
Let say i put my AWS url in the .env file.
AWS_URL=https://loremipsum.s3.ap-southeast-1.amazonaws.com
Is it possible to return the result from my query builder ?
You can use Laravel Raw Expressions and MySQL CONCAT function. E.g.:
$query = DB::table('subscriber')
->select([
'ID as SBC_ID',
'SUBSCRIBER_NAME',
DB::raw('CONCAT(\'https://loremipsum.s3.ap-southeast-1.amazonaws.com\', ATTACHMENT_OTHERS) as ATTACHMENT_OTHERS')
])->get();
Additionally, you put that url in .env
AWS_URL=https://loremipsum.s3.ap-southeast-1.amazonaws.com
and create new config file, e.g. config/aws.php
return [
'attachment_url' => env('AWS_URL', 'AWS_URL'),
]
and then you can have a little neater code:
$query = DB::table('subscriber')
->select([
'ID as SBC_ID',
'SUBSCRIBER_NAME',
DB::raw('CONCAT(\''.config('aws.attachment_url').'\', ATTACHMENT_OTHERS) as ATTACHMENT_OTHERS')
])->get();
If you returning this data via JSON API, then I suggest that you use Laravel API Resources
You can use SQL's built-in function CONCAT() with DB facade, something like like this:
use Illuminate\Support\Facades\DB;
// ...
$aws_host = "https://loremipsum.s3.ap-southeast-1.amazonaws.com" . "/";
$query = DB::table('subscriber')->select([
'ID as SBC_ID',
'SUBSCRIBER_NAME',
DB::raw('CONCAT("' . $aws_host . '", ATTACHMENT_OTHERS) AS ATTACHMENT_OTHERS'),
])->get();
$query = DB::table('subscriber')->select(['ID as SBC_ID','SUBSCRIBER_NAME','ATTACHMENT_OTHERS'])
->get();
$AWS_URL = "https://loremipsum.s3.ap-southeast-1.amazonaws.com/";
foreach($query as $result)
{
$SBC_ID = $result->SBC_ID;
$SUBSCRIBER_NAME = $result->SUBSCRIBER_NAME;
$ATTACHMENT_OTHERS = $AWS_URL.$result->ATTACHMENT_OTHERS;
}
$query = ([
'SBC_ID' => $SBC_ID,
'SUBSCRIBER_NAME' => $SUBSCRIBER_NAME,
'ATTACHMENT_OTHERS' => $ATTACHMENT_OTHERS
]);
return $query;

Populate WordPress Advanced Custom Fields with remote JSON in backend

I have custom post types called "Products". and using the AFC(Advanced Custom Fields) plugin with this post type.
Below is what ACF has in fields group
- one filed called 'Product Description' as text area
- three text fields called 'Feature 1, Feature 2,Feature 3'
What I want to achieve is to get the data from external JSON file and populate the above ACF fields in the backend. I did some research and found Wordpress offers wp_remote_get() function to request the remote file. But I have no clue where to begin with to use this function or any other approach to use external JSON and populate these fields. Will really appreciate it someone points me to the right direction or any tutorial that shows how to achieve that. Thanks
I figured it out. View the working code below.
// Get JSON and Decode
$json_request = wp_remote_get( 'http://wp-test/test/data.json');
if( is_wp_error( $json_request ) ) {
return false;
}
$json_body = wp_remote_retrieve_body( $json_request );
$json_data = json_decode( $json_body );
// Create the new post and populate the fields
foreach( $json_data->products as $item ) {
$title = $item->title;
$desc = $item->content;
$status = $item->status;
$new_post = array(
'post_title' => $title,
'post_content' => $desc,
'post_status' => $status,
'post_author' => $userID,
'post_type' => 'products'
);
$post_id = post_exists( $title );
if (!$post_id) {
$post_id = wp_insert_post($new_post);
}
}

Cakephp - How to return array content with array name

I want return the json data from my controller.
I have written belo code.
$this->loadModel('Users');
$query = $this->Users->find();
$users = $query->select(['id', 'name']);
echo json_encode($users);
This return data in below format:
[{"id":1,"news_type":1,"name":"hoge"},{"id":2,"news_type":1,"name":"hoge1"}]
but I want it in below format:
{"categories":[{"id":1,"news_type":1,"name":"hoge"},{"id":2,"news_type":1,"name":"hoge1"}]}
Found solution.
I have used this:
echo json_encode(array("users" => $users));

Fix the format of the retrieved data from the database using wordpress

I am retrieving data from database for multiple rows using the get_result() function in wordpress.
I am able to retrieve the required data but the format is wrong - how can I fix it?
Array ([0] => stdClass Object ( [siteNAME] => test0 )
I need the format to be:
test0, test1, test2
Code:
$result2 = $wpdb->get_results('select siteNAME from `site_info` where ownerID=159' );
print_r($result2);
Try 'echo' instead of 'print_r'.
With 'ownerID', check this code:
$result2 = $wpdb->get_results('select siteNAME from `site_info` where ownerID=159' );
foreach($result2 as $result) {
echo $result->siteNAME;
}
OR
Without 'ownerID', check this code:
$result2 = $wpdb->get_results('select siteNAME from `site_info` ');
foreach($result2 as $result) {
echo $result->siteNAME;
echo "<br/>";
}
print_r() function is mainly used for printing arrays.
Hope, this may be helpful for you.

Converting array to JSON object array

I am facing problem getting the JSON object array from the following code.
public function staffStatusFromSameDept($deptID)
{
$sameDeptEmployee=StaffsModel::where("DepartmentID","=",$deptID)->get();
$count=$sameDeptEmployee->count();
if ($count>0)
{
foreach ($sameDeptEmployee as $value)
{
$data=DB::table('status')
->join('staffs','status.StaffPin', '=', 'staffs.StaffPin')
->select('staffs.StaffName','staffs.DesignationName',
'status.staffStatus', 'status.currentLocation',
'staffs.EmailID','staffs.MobileNO','status.returnTime','staffs.Photo' )
->where('staffs.StaffPin','=',$value->StaffPin)
->get();
$response[]=$data;
}
}
else{
$response=["error" => "Invalid Department ID"];
}
header('Content-type: application/json');
echo json_encode($response);
}
Actual output:
[[{"StaffName":"Mamun hosen","DesignationName":"PO(MF)","staffStatus":"working","currentLocation":"rangpur","EmailID":"mamun#brac.net","MobileNO":"01716340278","returnTime":"04:30","Photo":"helal.jpg"}],[{"StaffName":"nahid
hasan","DesignationName":"PO(MF)","staffStatus":"working","currentLocation":"rangpur","EmailID":"nahid#brac.net","MobileNO":"01716340278","returnTime":"04:30","Photo":"helal.jpg"}]]
Expected output:
[{"StaffName":"Mamun hosen","DesignationName":"PO(MF)","staffStatus":"working","currentLocation":"rangpur","EmailID":"mamun#brac.net","MobileNO":"01716340278","returnTime":"04:30","Photo":"helal.jpg"},{"StaffName":"nahid
hasan","DesignationName":"PO(MF)","staffStatus":"working","currentLocation":"rangpur","EmailID":"nahid#brac.net","MobileNO":"01716340278","returnTime":"04:30","Photo":"helal.jpg"}]
The problem in my code is that each person details taking JSON object array. But I want one JSON object array and each of the person's details I will get from this JSON object array.
Because ->get() will return an array of records found.
So if your query always has 1 record, change ->get() to ->first(), otherwise use $response = array_merge($response, $data) instead of $response[] = $data
You can simply change the $response[]=$data; to $response=$data;