Cakephp - How to return array content with array name - cakephp-3.0

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));

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;

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.

How to post data as json in codeigniter?

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

Retrieve every model and return three values

I am looking for a way to retrieve all models in a database. Then loop through all of the models and read out the values for name, firstname and phonenumber.
So far I've gotten this and failed to go past it:
$searchModel = new EmployeeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
I am then looking to implement those three values in a simple HTML table:
<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>
The table should be part of a PDF output, so ideally I would save it to a variable:
$html_table = '<tr><td>$firstname</td><td>$name</td><td>$phone</td></tr>';
I would need to get this for every model that fulfills the criteria of status = 'active' in the database.
So far I've only been able to get tables via gridView and not in a HTML template either.
You don't really need a data provider to achieve this, you could simply try :
$models = Employee::find()->where(['status'=>'active'])->orderBy('name ASC')->all();
foreach ($models as $model) {
echo "<tr><td>{$model->firstname}</td><td>{$model->name}</td><td>{$model->phone}</td></tr>";
}
Read more : http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#querying-data
You can get all models like this:
$employees = Employee::find()
->select('firstname, name, phone')
->asArray()
->where(['status'=>'active'])
->all();
This way you will get an array of arrays containing the 3 selected fields, so now you only need to use a foreach to loop through them and create the table:
$html = '<table>';
foreach($employees as $employee) {
$html .= '<tr><td>'.$employee['firstname'].'</td><td>'.$employee['name'].'</td><td>'.$employee['phone'].'</td></tr>';
}
$html .= '</table>'

How to get array format data from json data in laravel4 query builder?

I am using laravel4 query builder . I have following query which returns json data .
$query=DB::connection('mysqlMagento')->
table('magento_catalog_category_flat_store_1')->
join('sohyper_region_activity', 'magento_catalog_category_flat_store_1.entity_id', '=', 'sohyper_region_activity.activity_id')->
select("magento_catalog_category_flat_store_1.entity_id" , "magento_catalog_category_flat_store_1.parent_id" , "magento_catalog_category_flat_store_1.name as label" ,"magento_catalog_category_flat_store_1.url_key as name")->
get();
The above query returns json format data , I want to convert this to arrat format . I know Toarray() is used in eloquent to convert this but here it is in query builder , please help me on this .
Thanks.
$query=DB::connection('mysqlMagento')->
table('magento_catalog_category_flat_store_1')->
join('sohyper_region_activity', 'magento_catalog_category_flat_store_1.entity_id', '=', 'sohyper_region_activity.activity_id')->
select("magento_catalog_category_flat_store_1.entity_id" , "magento_catalog_category_flat_store_1.parent_id" , "magento_catalog_category_flat_store_1.name as label" ,"magento_catalog_category_flat_store_1.url_key as name")->
get();
$array = json_decode($query);
Though i'm fairly sure that the query builder is not returning JSON.
The query builder returns an array of objects. For example the query:
$users = DB::table('users')->select('name')->get();
will return an array which you can handle like this
foreach($users as $user) {
echo $user->name;
}
EDIT
If you want to convert it to array you have to do it on your own.
Here is a quick way
$users = json_decode(json_encode($users), true);
Now you can handle it like this
foreach($users as $user) {
echo $user['name'];
}