How can I convert db query result to array - php

original I thought the $query is array object, since I can print these data to a list table like this.
my controller code
$data['dates'] = $this->calendar_model->get_cal_eventDate();
$this->load->library('table');
$this->load->view('my_test', $data);
my view code
echo $this->table->generate($dates);
but when I changed my code to try to print $tbDataArr via foreach. It didn't work. How can I convert the $query result (eventDate field values) to array object.
function get_cal_eventDate() {
$this->db->select('eventDate');
$query = $this->db->get('tb_event_calendar');
return $query;
}
$tbDataArr = $this->calendar_model->get_cal_eventDate();
foreach ($tbDataArr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}

Are you using CodeIgniter? If you are you can do this
function get_cal_eventDate() {
$this->db->select('eventDate');
$query = $this->db->get('tb_event_calendar');
$result = $query->result_array();
return $result;
}
If not need more info about what your doing with your PHP.

Codeigniter, right?
Use the $query->result_array() method.
see more here:
http://codeigniter.com/user_guide/database/results.html

//Convert $query->result_array() to $query->result() after add new field in array
$result = $query->result_array();
for($i=0;$i<$query->num_rows();$i++){
//insert new field in array (test_field with value 1)
$result[$i]+=array('test_field'=>1);
$result[$i] = (object)$result[$i];
}
return $result; //equivalent to return $query->result() without new field;

Related

How to compare associative array with result_array in PHP

Need to bind Page drop-down conditionally on base of 'Content' table. Page titles are stored in an associative array and 'Content' table have page code stored in it. Here is the code
Function which return page titles
public function getPageTitles(){
$pageTitles = array("Home"=> "Home",
"AboutUs"=> "About Us", //AboutUs will save in database as pageCode
"Features"=> "Features",
"ContactUs"=> "Contact Us");
return $pageTitles;
}
Function which checks if page have content or not:
public function getPageTitlesWithNoContent()
{
$pageTitles = $this->getPageTitles();
$this->db->distinct('pageCode');
$this->db->select('pageCode');
$this->db->from('content');
$this->db->where('status', 1);
$data = $this->db->get();
$queryResult = $data ? $data->result_array() : 0 ;
$emptyPageTitle = array();
foreach($pageTitles as $x => $x_value)
{
$hasContent = in_array($x, $queryResult);
if (!$hasContent){
$emptyPageTitle[$x] = $x_value;
}
}
return $emptyPageTitle;
}
This function is returning all page titles.. new to php no idea what is wrong
Check name fields in table is same? With Uppercase first char?
Also change your code in this loop:
foreach($pageTitles as $x => $x_value)
{
if (in_array($x, $queryResult)){
$emptyPageTitle[$x] = $x_value;
}
}
I remove ! negative in check condition
#NMathur I think you almost got it. Made some changes for you in that code, Check it.
public function getPageTitlesWithNoContent() {
$pageTitles = $this->getPageTitles();
$this->db->select('pageCode');
$this->db->from('content');
$this->db->where('status', 1);
$this->db->group_by('pageCode');
$query = $this->db->get();
$queryResult = array();
foreach ($query->result_array() as $row) { // This loop should need to form an array based on query result
$queryResult[$row['pageCode']] = $row['pageCode'];
}
$emptyPageTitle = array_diff_key($pageTitles,$queryResult); // Compares the keys from array1 against the keys from array2 and returns the difference
return $emptyPageTitle;
}
As #TamilvananN guided, I printed the queryResult and tried this workaround:
foreach($pageTitles as $x => $x_value)
{
foreach ($queryResult as $item)
{
if (!($x == $item['pageCode'])){
$emptyPageTitle[$x] = $x_value;
}
}
}
It is working, but as you can see this has loop in a loop .. that can be very costly .. can you please share any fast way to compare the results.

How do I build this array to output?

I have the following function which fetches some data from a MySQL table:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
var_dump($row);
};
echo $data
}
How can I push all the returned data into an array, where each member is indexed by a number?
Do I need to use echo or return at the end? They seem to have the same effect.
EDIT: Is this the correct way of returning results of the query? I am passing it to the front-end.
$questionData = $controller->readQuestion($quizType, $questionId);
return $questionData;
In general your function must looks like:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
return $query;
}
But, you have to look what is inside $query variable. If it is array - just return this array, if not - maybe it is some iterator, hence you have to check it and try to find method like toArray or something like that... Otherwise, you have to do something like:
$data = [];
foreach ($query as $row) {
$data[] = $row;
};
return $data;
Now you can use this function like:
var_dump(readQuestion($quizType, $questionId));
Take a look up here on how to secure your data.
Anyway, as I said in the comment you cannot use echo on an Array. And you can't do anything with the output of var_dump.
Change var_dump($row); for $data[] = $row;
and change echo $data; for return $data;
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
$data=$row;
};
return $result;
}

Return the highest value from model to view

I want to know how to compare these 2 outputs http://prntscr.com/bx7ay9 and return the highest value in the array ?
MY MODEL CODES
$this->db->select('additional');
$this->db->from('order_detail');
$this->db->where('order_id',$id);
$query = $this->db->get();
foreach ($query->result() as $row)
{
$return[] = $row->additional;
}
return $return;
Just use select_max in query to get highest value and use row() to fetch single row without using foreach loop as
$this->db->select_max('additional AS max_value');
$this->db->from('order_detail');
$this->db->where('order_id', $id);
$query = $this->db->get();
$ret = $query->row();
return $ret->max_value;
$this->db->select('additional');
$this->db->from('order_detail');
$this->db->where('order_id',$id);
$query = $this->db->get();
foreach ($query->result() as $row)
{
$return[] = max($row->additional);
}
return $return;
Just used select_max of Codeigniter Query Bulder Class.
Model,
public function get_max ($id){
$this->db->select_max('additional');
$this->db->where('order_id',$id);
$query = $this->db->get('order_detail');
return $query->row();
}
In Controller,
$max = $this->Model->get_max($id);
echo $max['additional']; // Display and see the value.
If you want to get the max number then use select_max(),
$this->db->select_max('additional');
$this->db->from('order_detail');
$this->db->where('order_id',$id);
$query = $this->db->get();
if($query->num_rows()){// check if data is not empty
return $query->row()->additional;
}
return false;// you can return false here
And if you want to get the result array for another use then, you can use max() with $this->db->select('additional'); with your code to get the max number in array.

CodeIgniter - return paramater as row

This is my code as of now which returns Hassum Harrod profile as JSON which is perfect. What I need to happen is for my parameter to be passed into the query string instead of having a name so that when the url is passed a name the query returns that person's profile from the DB. When I change the name Hassum Harrod to the variable $name I get the following error:
Unknown column 'Hassum' in 'where clause'
SELECT name, short_name, reknown, bio FROM profile WHERE name = Hassum%20Harrod
This is my code as now:
Controller
public function getPerson($name) {
// loads the DBModel.php
$this->load->model('DBModel');
$query = $this->db->query("SELECT name, short_name, reknown, bio FROM profile WHERE name = 'Hassum Harrod'");
$data['profile'] = $query->row();
$this->load->view('profileView', $data);
}
View
echo json_encode($profile);
Please Read : http://www.codeigniter.com/user_guide/general/models.html
http://www.codeigniter.com/user_guide/database/query_builder.html
Try this way
Add this method to your model it should be like this
// in your model
public function getNames($name) {
$data = array();
$this->db->select(*);
$this->db->like('name', $name);
$query = $this->get('profile');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data[] = $row;
}
}
return $data;
}
Your Controller should be like this
public function getPerson($name) {
$this->load->model('DBModel');
$data = $this->DBModel->getNames($name);
// you can encode in json here
$data['profile'] = json_encode($data);
$this->load->view('profileView', $data);
}
http://www.codeigniter.com/user_guide/general/controllers.html
In view :
echo $profile;
You are using LIKE keyword in your query so we could assume there would be more than one result in return from DB. In that case you would need $query->result() instead. Secondly, even if there is just one returned row, this code:
$data['profile'] = $query->row() > 0;// assigning variable to condition (TRUE|FALSE)
will return boolean value, but not result itself.
This is simplified code for that and you can check:
<?php
$a = ['a', 'b', 'c'];
var_dump($b = $a > 0);// TRUE
Feel free to start using basic examples from docs. It will help you maintaning code:
$query = $this->db->query("YOUR QUERY");
$row = $query->row();
if (isset($row))
{
echo $row->title;
echo $row->name;
echo $row->body;
}
Again, if you expect only one possible row from DB, you can try with this code. But if you are not certain if there would be several possible rows, you have to use code for retreiving that:
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
When you set this all working than you can work on converting object or array to JSON string.
It would follow syntax:
$json = json_encode($row);
If multiple rows is returned, it would be most easier to return result_array() or row_array() from DB since arrays are easily converted ti JSON, although there are suitable solutions.
After all, model that is loaded at the beginning of method is not used at all.
Docs.

get value single value from array var that stores result of query php

I have a query that stores result of query like
$this->load->model('person/person_model');
$data['result'] = $this->person_model->get('tbl_person', array('id_person' => $some_key),TRUE);
this will return all the fields of person with $some_key (id,name,email...)
Then I need to pass $data but before I would like to use name and email of that result
so
$this->load->model('person/other_person_job_model');
$status= $this->other_person_job_model->get('tbl_other_person',array('name'=> ? ),TRUE);
Then I could use $status['name'] or $status['email']
What should I put instead of ? in the example above?
Should I use $data['result']['name'] or something like that?
the get function is:
function get($table,$where=array(),$single=FALSE) {
$q = $this->db->get_where($table,$where);
$result = $q->result_array();
if($single) {
return $result[0];
}
return $result;
}
you could use variable, like:
$this->load->model('person/person_model');
$result = $this->person_model->get('tbl_person', array('id_person' => $some_key),TRUE);
$data['name'] = $result->name;
$data['result'] = $result;
//and
$this->load->model('person/other_person_job_model');
$status= $this->other_person_job_model->get('tbl_other_person',array('name'=> $result->name ),TRUE);

Categories