codeigniter single result without foreach loop - php

I am using codeigniter to get a single result from the db, like this:
$user = $this->db->query("SELECT * FROM users LIMIT 1");
I am then getting the returned object and looping trough it, this way:
foreach ($user->result() as $row) { ... }
As you can imagine, there is not point in using the loop, since there is only one result. Is there a way to get users parameters without looping? Something among this line:
echo $user['name'];
Thanks in advance.

$user = $this->db->query("SELECT * FROM users LIMIT 1")->row();
for having it as an object ( echo $user->name;)
$user = $this->db->query("SELECT * FROM users LIMIT 1")->row_array();
for having is as an array ( echo $user['name']; );
$user = $this->db->limit(1)->get('users')->row(); //or ->row_array();
using AR;
$row = $user->first_row();
to get the first row out of a result set ($this->db->result()), as an object (default);
$row = $user->first_row('array');
to get the first row out of a result set, as an array;
$row = $user->row_array(1);
to return a specific row (first, in this case. Just pass the <N> of the row). Works also for $user->row(1);

It would be:
$user = $this->db->query("SELECT * FROM users LIMIT 1")->row_array();
More details here: http://ellislab.com/codeigniter/user-guide/database/results.html

do something like this
//in the model
$query = $this->db->query("your query");
$row = $query->row();
if (isset($row))
return $row;
}else{
return false;
}
then echo your results like this
echo $row->username;
if you want to pass it to a view
//in the controller
$this->load->model('somemodel');
$hm=$this->somemodel->somemethod();
$data['query']=$hm;
$this->load->view('path/to/view',$data);
Then echo the same way
echo $row->username;

Suppose for example your model function is like this.......
public function get_users()
{
$query = "Select * from users limit 1";
$res=$this->db->query($query);
if($res->num_rows()>0){
return $res->result("array");
}
return array();
}
Suppose you are calling this model in your controller function like this
$users = $this->model_file->get_users();
then you can echo like this echo $users[0]['user_name'];

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

how to get db all data using array in php

I create as the following function. how to get all data using this array. when run this function will appear only the first record. but, i want it to appear all the records. what is the error in this code.
public function get_All_Se($stId){
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
$data = $result->fetch_array(MYSQLI_ASSOC);
return $data;
}
public function get_All_Se($stId){
$rows=array();
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
while($data= $result->fetch_assoc()){
$rows[]=$data;
}
return $rows;
}
Run loop over all results and add to some return array.
$rows = array();
while(($row = $result->fetch_array($result))) {
$rows[] = $row;
}
As the documentation of mysqli::fetch_array() explains, it returns only one row (and not an array containing all the rows as you might think).
The function you are looking for is mysqli::fetch_all(). It returns all the rows in an array.
public function get_All_Se($stId)
{
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
return $result->fetch_all(MYSQLI_ASSOC);
}
The code above still has two big issues:
It is open to SQL injection. Use prepared statements to avoid it.
or die() is not the proper way to handle the errors. It looks nice in a tutorial but in production code it is a sign you don't care about how your code works and, by extension, what value it provides to their users. Throw an exception, catch it and handle it (log the error, put some message on screen etc) in the main program.
Try this way...
<?php
// run query
$query = mysql_query("SELECT * FROM <tableName>");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['<fieldName>']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['<fieldName>'];
?>

PHP PDO FetchAll vs Fetch

I believe I am using the PDO fetch functions completely wrong. Here is what I am trying to do:
Query a row, get the results, use a helper function to process the results into an array.
Query
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$qr = $q->fetchAll(PDO::FETCH_ASSOC);
if ($qr->rowCount() > 0){
foreach($qr as $row){
$names[$row['id']] = buildArray($row);
}
return $names;
}
}
My custom array building function
function buildArray($row){
$usernames = array();
if(isset($row['id'])) $usernames['id'] = $row['id'];
if(isset($row['name'])) $usernames['name'] = $row['name'];
}
I'm actually getting exactly what I want from this, but when I echo inbetween I see that things are looping 3 times instead of once. I think I am misusing fetchAll.
Any help appreciated
If you're going to build a new array, there's not much point in having fetchAll() build an array. Write your own fetch() loop:
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$names = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$names[$row['id']] = $row;
}
return $names;
}
There's also no need for buildArray(), since $row is already the associative array you want.

Selecting records from a database table in PHP using CodeIgniter and pass to a view

I'm making a query in PHP using CodeIgniter to get the data that I wanted from a database. To be able to get all values for a specific column, I stored it into an array and passed it into a view. But I can do it only for one column.
Here's my code:
$query = $this->db->query('SELECT name, description FROM module');
$result = $query->result_array();
foreach ($result as $key => $rowdata) {
$resultdata['values'][$key] = $rowdata['name'];
}
$this->load->view('myview', $resultdata);
With this scenario I can get all name from the module table. But my problem is, I also wanted to get all the description in the module table, but I don't know how can I implement it and be able to pass it into the view. Hope someone could help me with this. Thanks!
Your not using the MVC pattern!
First you should write your query in a model!
Then load it in your controller like this
$this->load->model('ModelName');
Then call the funcion to retreive the data
$data = $this->modelname->functionToRetreiveData();
Then loop through data with foreach
$dataToView = array();
foreach($data as $key=>$row)
{
$dataToView['something'][$key]['value'] = $row->name_of_column;
}
And pass the array to the view $this->load->view('someview',$dataToView);
Then in the view
foreach($value as $val):
<p><?php echo $val['name']?><p>
endforeach
hi in you way you will do loop twice in controller and then in view to print it check this out
//in controller
$query = $this->db->query('SELECT name,description FROM module');
$resultdata['results'] = $query->result_array();
$this->load->view('myview',$resultdata);
myview.php
foreach($results as $result)
{
echo $result['name'],' ',$result['description'];
}
$query = $this->db->query('SELECT name,description FROM module');
$result = $query->result_array();
foreach($result as $rowdata){
$resultdata['values'][] = $rowdata;
}
$this->load->view('myview',$resultdata);
Try in view:
print_r($values);
You will probably have:
$result[0]['name'], $result[0]['description'] ...
$this->load->database();
$this->db->select('employee');
$query = $this->db->get();
return $query;
foreach ($query as $row) {
print $row->'Name';
.
.
.
print $row->'Address';
}

How do you create a simple function to query the database? Mine isn't working!

I want to make a simple function that I can call on to query my database. I pass the "where" part of the query to it and in the code below, my $q variable is correct. However, what should I then do to be able to use the data? I'm so confused at how to do something I'm sure is extremely easy. Any help is greatly appreciated!
function getListings($where_clause)
{
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q,$dbh);
foreach (mysql_fetch_array($result) as $row) {
$listingdata[] = $row;
}
return $listingdata;
}
Your function should be like this:
function getListings($where_clause, $dbh)
{
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q, $dbh);
$listingdata = array();
while($row = mysql_fetch_array($result))
$listingdata[] = $row;
return $listingdata;
}
Improvements over your function:
Adds MySQL link $dbh in function arguments. Passit, otherwise query will not work.
Use while loop instead of foreach. Read more here.
Initialize listingdata array so that when there is no rows returned, you still get an empty array instead of nothing.
Do you have a valid db connection? You'll need to create the connection (apparently named $dbh) within the function, pass it in as an argument, or load it into the function's scope as a global in order for $result = mysql_query($q,$dbh); to work.
You need to use while, not foreach, with mysql_fetch_array, or else only the first row will be fetched and you'll be iterating over the columns in that row.
$q = "SELECT * FROM `listings` $where_clause";
$result = mysql_query($q,$dbh);
while (($row = mysql_fetch_array($result)) != false)
{
$listingdata[] = $row;
}
Always add error handling in your code. That way you'll see what is going wrong.
$result = mysql_query($q,$dbh);
if (!$result) {
trigger_error('Invalid query: ' . mysql_error()." in ".$q);
}
Here is a function which will save you some time. First Argument tablename, then condition(where), fields and the order. A simple query will look like this : query_db('tablename');
function query_db($tbl_name,$condition = "`ID` > 0",$fields = "*",$order="`ID` DESC"){
$query="SELECT ".$fields." FROM `".$tbl_name."` WHERE ".$condition." ORDER BY".$order;
$query=$con->query($query);
$row_data=array();
while($rows = $query->fetch_array()){
$row_data[] = $rows;
}
return $row_data;
}

Categories