Codeigniter SELECT from TABLE problems - php

I have this code, in my Model:
public function get_all_distinct() {
$query = 'SELECT DISTINCT(tag) FROM `tags_to_questions`';
$result = array(
'assignedTags' => array(),
'availableTags2' => $this->db->query($query)->result_array(),
);
return json_encode($result);
}
}
And this code will return me an array (json type) like:
{"assignedTags":[],"availableTags2":[{"tag":"php"},{"tag":"mysql"}]}
What to change in my code to get an array like:
{"assignedTags":[],"availableTags2":[{"php"},{"mysql"}]}
I just need the values from the key, not with the key.

I don't think this is a feasible or not but you can use array_column as
public function get_all_distinct() {
$query = 'SELECT DISTINCT(tag) FROM `tags_to_questions`';
$result = array(
'assignedTags' => array(),
'availableTags2' => $this->db->query($query)->result_array(),
);
$result['availableTags2'] = array_column($result['availableTags2'],'tag');
return json_encode($result);
}
}

You will need a foreach to do so. There is no automatic way.
$tmp = $this->db->query($query)->result_array();
foreach($tmp as $cell=> $row) {
$tmp_result[] = $row;
}
$result = array(
'assignedTags' => array(),
'availableTags2' => $tmp_result,
);
return json_encode($result);

Use array_values(). This will do:
public function get_all_distinct() {
$query = 'SELECT DISTINCT(tag) FROM `tags_to_questions`';
$result = array(
'assignedTags' => array(),
'availableTags2' => array_values($this->db->query($query)->result_array()),
);
return json_encode($result);
}
}

Related

Yii2 multiple models loop save error

I've a table in which I have to save multiple data, in my controller I've implemented this action:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
$model = new SlidersImages();
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
if ($model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()) {
$s['image_'.$key] = $model;
$model->display_order = $value;
//$result = ($t = $model->update()) ? $result + $t : $result;
$result = $model->save() && $result;
}
}
}
return $result;
}
The data received are right but not the result, the only thing that the action do is to add new table row with slider_id and image_id equal to NULL, why the model doesn't save correctly?
Thanks
The thing is when you call
$model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
you don't change the $model object itself. Essentially you are calling:
SlidersImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
So, later when you call $model->save() you are saving a $model object with empty attributes (you only changed display_order)
My advise here: try to assign the result of the ->all() call to the new var and then work with it:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
$models = SliderImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all();
if (count($models)) {
// loop through $models and update them
}
}
}
return $result;

DB query returns only first matching result

// Get all categories
$query = "SELECT name FROM bolt_taxonomy WHERE taxonomytype = :taxonomytype AND contenttype = :contenttype";
$map = array(
':taxonomytype' => 'categories',
':contenttype' => 'news',
);
$categories = $this->app['db']->fetchAssoc($query, $map);
$response = $this->app->json(array('categories' => $categories));
return $response;
Returns:
{
"categories": {
"name": "life"
}
}
Which is just the first entry that matches the above condition on the bolt_taxonomy table. How can I get it to return the whole list of categories?
This is now solved by using fetchAll:
// Get the category
$query = "SELECT name FROM bolt_taxonomy WHERE taxonomytype = 'categories' AND contenttype = 'news'";
$categories = $this->app['db']->query($query);
$result = $categories->fetchAll();
$response = $this->app->json(array('categories' => $result));
return $response;
You need to populate using while or foreach loop.
$categories = $this->app['db']->fetchAssoc($query, $map);
foreach($categories as $category) {
$result[] = $category;
}
$response = $this->app->json($result);
echo $response;
return $response;

change key names in array in php

ok..I'm trying to re-map the keynames of a key-value array in php using a fieldmap array ie.
i want the $outRow array to hold $inRow['name1'] = 10 to $outRow['name_1'] = 10 for a large set of pre-mapped values..
$fieldmap=array("name1"=>"name_1","name2"=>"name_2");
private function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[$this->fieldmap[$key]][] = $value;
}
return $outRow;
} // end mapRow
public function getListings($inSql) {
// get data from new table
$result = mysql_query($inSql);
if (!result) {
throw new exception("retsTranslate SQL Error: $inSql");
}
while ($row = mysql_fetch_assoc($result)) {
$outResult[] = $this->mapRow($row);
}
return $outResult;
} // end getListings
this is not working..I'm getting the array but its using $outResult[0][keyname]...I hope this is clear enough :)
$fieldmap=array("name1"=>"name_1","name2"=>"name_2");
private function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[$this->fieldmap[$key]][] = $value;
}
return $outRow;
} // end mapRow
while ($row = mysql_fetch_assoc($result)) {
//$outResult[] = $this->mapRow($row);
$outResult[= $this->mapRow($row);
}
I commented your line of code and added new one..it definitely got what you mentioned in question.
If you can structure your arrays to where the keys align with the values (see example below) you can use PHP array_combine(). Just know that you will need to make absolutely sure the array is ordered correctly.
<?php
$fieldmap = array( 'name_1', 'name_2', 'name_3' );
private function mapRow($inRow)
{
$outRow = array_combine( $this->fieldmap, $inRow );
return $outRow;
}
For example, if your array was:
array( 'name1' => 10, 'name2' => 20, 'name3' => 30 );
The new result would be:
array( 'name_1' => 10, 'name_2' => 20, 'name_3' => 30 );
Let me know if this helps.
Try this:
function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[preg_replace('/\d/', '_$0', $key,1)] = $value;
}
return $outRow;
}

How to access array computer by a function within Codeigniter?

I have a function as follow:
function get_employee_information()
{
$this->db
->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
}
I'm trying to access this data from within an output to template, like this:
$this->get_employee_information();
$output = $this->template->write_view('main', 'records', array(
'employee_names' => $employee_names,
'employee_ids' => $employee_ids,
), false);
Yet this isn't displaying anything. I feel like this is something small and I should know better. When I tun print_r($arrayname) on either array WITHIN the function, I get the suspected array values. When I print_r OUTSIDE of the function, it returns nothing.
Your function is not returning anything. Add the return shown below.
function get_employee_information()
{
$this->db->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
return array(
'employee_names'=>$employee_names,
'employee_ids'=>$employee_ids,
);
}
You are not setting the return value of the function to a variable
$employee_info = $this->get_employee_information();
$output =
$this->template->write_view(
'main', 'records',
array(
'employee_names' => $employee_info['employee_names'],
'employee_ids' => $employee_info['employee_ids'],
),
false
);

Storing data in a session, can only seem to store 1 piece of data at a time

I am trying to allow the user to create a shortlist, however I add one thing the shortlist, and it overwrites the whatever else is in there, what am I doing wrong?
function validate_add_cart_item($id){
$this->db->select('candidates.candidate_id, candidates.first_name, candidates.surname, candidates.DOB, candidates.talent, candidates.location, candidates.availability_order, candidates.availability, candidates.availability_comments, candidate_assets.url, candidate_assets.asset_size')
->from('candidates')
->join('candidate_assets', 'candidate_assets.candidates_candidate_id = candidates.candidate_id', 'left')
->where('candidate_assets.asset_size', 'small')
->where('candidate_assets.asset_type', 'image')
->where('candidates.candidate_id', (int)$id)
->limit(1)
->order_by('candidates.availability_order', 'DESC');
$query = $this->db->get();
//die($this->db->last_query());
// Check if a row has been found
if($query->num_rows > 0 ){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'name' => $row->first_name." ".$row->surname,
'location' => $row->location,
'talent' => $row->talent,
'image' => $row->url
);
$this->session->set_userdata('shortlist', array($data));
return TRUE;
}
// Nothing found! Return FALSE!
} else {
return FALSE;
}
foreach(...){
// ...
$this->session->set_userdata('shortlist', array($data));
}
You are overwriting your previous userdata several times. Instead of this you should create an array, and call set_userdata once.
$udata = array();
foreach(...){
// ...
$udata []= $data;
}
$this->session->set_userdata('shortlist', $udata);
edit:
And your query returns only one row, you probably want to update your array, not overwrite it, so something like this:
$udata = $this->session->get_userdata('shortlist');
foreach(...){
// ...
$udata []= $data;
}
$this->session->set_userdata('shortlist', $udata);
$this->session->set_userdata('shortlist', array($data));
doesn't append $data to shortlist but overwrites it with an array that has one element: the current data in $data.
You probably (untested) want:
if($query->num_rows > 0 ) {
$data = array();
foreach ($query->result() as $row)
{
// append the new "record" to the array $data
$data[] = array(
'id' => $id,
'name' => $row->first_name." ".$row->surname,
'location' => $row->location,
'talent' => $row->talent,
'image' => $row->url
);
}
$this->session->set_userdata('shortlist', $data);
return TRUE;
}
else {
...

Categories