getting a value from a resultset with Codeigniter - php

In my model I have this snippet
$this->db->select('*');
$this->db->from('User');
$this->db->where('email', $mail);
$query = $this->db->get();
return $query;
As far as I know, $query is an array (a set of results), I want to retrieve an specific value of a field in that array to return it or to assign it to another variable, the question is HOW?
I'd like to do something like this
$value = $query['first_field_of_resultset'];
return $value;

extending Johns answer, you need to cover yourself in case nothing comes back
so in your model method:
// make sure we have a result
if ( $query->num_rows() == 1 )
{
// assign the result
$user = $query->row();
// pull out the field you want
$value = $user->first_field_of_resultset;
// return it
return $value ;
}
else { return FALSE; }
Then in your controller, say if the model is called user_model
if(! $value = $this->user_model->getUser($email) )
{
// boo hoo no results
}
else
{
// success
}
And of course this assumes you have run $email through CI form validation to make sure it is a valid email -- before sending to your database.

There's a bunch of different ways to get the results. Here's one:
$user = $query->row();
echo $user->first_field_of_resultset;
If you prefer arrays:
$user = $query->row_array();
echo $user['first_field_of_resultset'];

If you want the first row you can do:
$row = $query->first_row();
But I don't know why you are retreaving all fields if you only need just one column:
$this->db->select('user.the_column_to_select');

$query is an object. So in order to get the results as an array you need to do the following.
$result = $query->result_array();
return $result[0];

You can try this also:
$email = $this->db->select('email')->from('users')->where(array(
'userID' => $userID))->limit(1)->get()->row('email');
// $email will either be the email address you're looking for or FALSE

Related

Print count value in codeigniter

I want to print count of some records in my project , i tried using some code but no result is giving can anyone figure out the mistake please.
controller
function cart_count()
{
$sess = $this->session->userdata('SESS_USER');
$query = $this->product_model->c_count($sess);
$data['count'] = $query->result();
$query = $this->db->get("cart");
$data['records'] = $query->result();
$this->load->view('frontend/menu',$data);
}
Model
public function c_count($sess)
{
$query =$this->db->query("SELECT COUNT(`product_id`) FROM `cart` WHERE `username`='$sess'");
return $query;
}
View
<?php foreach($count as $count){echo $count;}?>
I see your query using count and where. That is mean you just select 1 row of data like this.
username COUNT(product_id)
admin 3
The return data is just 1 row, so you can return the data using row() like this return $query->row().
Model : return your data default as a row() for 1 row of data.
public function c_count($sess)
{
$query = $this->db->query("SELECT COUNT(product_id) as count_id
FROM cart
WHERE username = '$sess'");
return $query->row();
}
Controller : Call your data here.
function cart_count()
{
$sess = $this->session->userdata('SESS_USER');
$query = $this->product_model->c_count($sess);
$data['count'] = $query->count_id; // CHANGE FROM $data['count'] = $query->result();
// If you dont mind, I change your code :
// $query = $this->db->get("cart");
// $data['records'] = $query->result();
$record = $this->db->get("cart");
$data['records'] = $record->result();
$this->load->view('frontend/menu',$data);
}
Views Here is how to call your data, ill give example using <span>.
<span>Admin total product : <?php echo $count; ?> Products</span>
There is so many ways to call returned data from database.
You can also use <?php echo $query->count_id; ?> in your views without set it into $data['count'] in your controller. You can try it now. :) Hope this help.
Note : If you want to call more than 1 data, dont use where but use a group by. I want to give you an example for that, but it's a different problem with your question. :) and if there any typos, please let me know and I will fix it.
$query =$this->db->query("SELECT COUNT(`product_id`) AS count FROM `cart` WHERE
`username`='$sess'");
change the query to
$query =$this->db->query("SELECT COUNT(`product_id`) as count FROM `cart` WHERE `username`='$sess'");
$query->result() will return array of objects
in view you will get as object you can use
<?php foreach($count as $count){echo $count->count;}?>
or
<?php echo $count[0]->count?>
The issue is with your model class where you fetch the number of row counts.
Actually, in CodeIgniter the result set fetched matches with what the columns of DB tables are.For eg. the statement
$query =$this->db->query("SELECT COUNT(`product_id`) FROM `cart` WHERE `username`='$sess'");
will return a result set something like this
Array ( [0] => stdClass Object ( [COUNT(`product_id`)] => 60 ) )
And when you try to display the result with this line <?php foreach($count as $count){echo $count;}?>
you get error because you are asking to show $count data variable of $count array which is not present.
One simple trick to solve this problem without much changes in your code is to use alias in your query.Just change your query to this
$query =$this->db->query("SELECT COUNT(`product_id`) as 'nums' FROM `products` WHERE `service_id`='$sess'");
And fetch the result in the view as <?php foreach($count as $c){echo $c->nums;}?>
However,in my opinion its better to use inbuilt function num_rows() of CI for this.
Simply use PHP count() function after getting the result
CONTROLLER
function cart_count()
{
$sess = $this->session->userdata('SESS_USER');
$query = $this->product_model->c_count($sess);
$data['count'] = count($query->result());
$query = $this->db->get("cart");
$data['records'] = $query->result();
$this->load->view('frontend/menu',$data);
}

Codeigniter/PHP: How to merge distinct arrays and make it unique into one array in query result

- ingredient
- menu
recipe
How will I merge the two array under name into one array and make it unique. As you can see the result on the [0] is
Beef Adobo
qwerty
iswi
and on 1 is
qwerty
iswi
I want the both of them to be in one array and the result should be
Beef Adobo
qwerty
iswi
query:
public function get_halal($name) {
$terms = explode(',', $name);
foreach ($terms as $name) {
$this->db->distinct();
$this->db->select('r_name');
$this->db->from('recipe');
$this->db->join('menu', 'menu.recipe_id = recipe.recipe_id');
$this->db->join('ingredient', 'ingredient.ingredient_id = menu.ingredient_id');
$this->db->where('menu.category_id = 2');
$this->db->like('ingredient.name', $name);
$query = $this->db->get()->result();
$data[] = $query;
}
return $data;
}
controller:
public function ajaxSearchHalal() {
postdata = file_get_contents("php://input");
if (isset($postdata)) {
$post = json_decode($postdata);
$name = $post->name;
if ($this->user_model->get_halal($name)) {
$user_id = $this->user_model->get_halal($name);
$data = array(
'name' => $user_id,
);
echo json_encode($data);
} else {
echo json_encode("false");
}
} else {
echo "Error!";
}
}
Ok, I see what you are doing now. Thanks for including your tables.
From what I see, you are trying to get all the recipe names, from the recipe table, that have the ingredients your are passing.
What you need to do to fix this issue is not worry about how to merge the arrays, but how you can redo your sql query in order to obtain the information you want in just one query. The way you have it now is not efficient as you are calling a query per every iteration.
What you need to do is use WHERE IN, and GROUP BY to get the info you need and group them by a column. Redo your model method like this:
public function get_halal($name) {
$terms = explode(',', $name);
$this->db->select("r.name");
$this->db->from('recipe r');
$this->db->join('menu m', 'm.recipe_id = r.recipe_id');
$this->db->join('ingredient i', 'i.ingredient_id = m.ingredient_id');
$this->db->where('m.category_id = 2');
$this->db->where_in('i.name', $terms);
$this->db->group_by('r.recipe_id');
$q = $this->db->get();
return $q->result();
}
This will give you one result set which you can then pass as JSON to your front-end without having to iterate or merge arrays.
Hope this helps.

return the columns of a result row as an array that can be referenced by index in codeigniter / active record

I am getting a specific row in a database with codeigniter / php /active record. I a would like to return the result as an array of the row's columns that can be referenced like this:
result[0] = column1
result[1] = column2
...
This is my current query:
public function get_instance($instanceID = NULL){
$this->db->select('organism, feature, goal');
$this->db->from('extra_instances');
$this->db->where('id', $instanceID);
$query = $this->db->get();
return $query->row_array();
}
$data['instance'] = $this->instances_model->get_instance($instanceID);
But currently, to echo these, I (think) I need to give the name of the column, like:
<?php echo($instance['goal']) ; ?>
Is there a way to do this so I can say:
<?php echo($instance[2]) ; ?>
You can do this by create a new array and assigns all values of old array to new array.
You can use the array_values() function to do this.
Here is the example. so you can get more idea.
public function get_instance($instanceID = NULL){
$this->db->select('organism, feature, goal');
$this->db->from('extra_instances');
$this->db->where('id', $instanceID);
$query = $this->db->get();
$results = $query->row_array();
return array_values($results);
}

I want to fetch specific data from a table using zend model class using this->select

public function getDataByMenuId($menu_id)
{
$select = $this->select()->where('menu_id=?', $menu_id);
$result = $this->fetchAll($select);
if ($result) {
return $result->toArray();
} else {
return NULL;
}
}
the above code fetching all the data from the table but i want only some data in the table
Edit: I mean to say I want fetch some columns of every row any thanks for your reply
Only some? Some? Really? :)
If "SOME" = 4
then You can use:
$select = $this->select()->where('menu_id=?', $menu_id)->limit(4);
You can try also:
$select = $this->select()->where('menu_id=?', $menu_id)->limit(SOME);
If You have defined Your some constant ;)

Changing database results in model as object

In past Codeigniter projects, I have always used $query->result_array() instead of $query->result()
For example, as an array, I would have the following in a model:
$this->db->select('id, username');
$this->db->from('users');
$query = $this->db->get();
$result = array();
foreach ($query->result_array() as $row)
{
$id = $row['id'];
$result[$id]['id'] = $row['id'];
$result[$id]['username'] = strtolower($row['username']);
)
return $result;
It can get really messy with more records and I have to add all of the fields even if I just need to perform operations on only one of them.
Now, for my current project, I am trying to just $query->result(), which is just an array of objects, but I'm not sure how to perform operations on them and return the results.
For example, if I'm using $query->result() and I want to make every username lowercase (strtolower), how would I perform those changes in the model?
The answer to your example and comment:
$results = $query->result();
foreach($results as $result){
$result->username = strtolower($result->username);
}
return $results;
foreach($query->result() as $row){
$username_lower = strtolower($row->username);
//if you want to actually update the record in the db
$this->db->where('id',$row->id);
$this->db->update('users', array('username' => $row->username));
}

Categories