At the moment if I am doing a query on the database that should only return one row, using:
...query stuff...
$query = $this->db->get();
$ret = $query->result();
return $ret[0]->campaign_id;
Is there a CodeIgniter function to return the first row?
something like $query->row();
Or even better would be the ability to, if there was only one row,
to just use the query object directly.
e.g. $query->campaign_id;
You've just answered your own question :)
You can do something like this:
$query = $this->db->get();
$ret = $query->row();
return $ret->campaign_id;
You can read more about it here: http://www.codeigniter.com/user_guide/database/results.html
This is better way as it gives you result in a single line:
$this->db->query("Your query")->row()->campaign_id;
To add on to what Alisson said you could check to see if a row is returned.
// Query stuff ...
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$row = $query->row();
return $row->campaign_id;
}
return null; // or whatever value you want to return for no rows found
To make the code clear that you are intending to get the first row, CodeIgniter now allows you to use:
if ($query->num_rows() > 0) {
return $query->first_row();
}
To retrieve the first row.
$this->db->get()->row()->campaign_id;
Change only in two line and you are getting actually what you want.
$query = $this->db->get();
$ret = $query->row();
return $ret->campaign_id;
try it.
If you require to get only one record from database table using codeigniter query then you can do it using row(). we can easily return one row from database in codeigniter.
$data = $this->db->get("items")->row();
We can get a single using limit in query
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
You can do like this
$q = $this->db->get()->row();
return $q->campaign_id;
Documentation :
http://www.codeigniter.com/user_guide/database/results.html
Option 1
$limit = 1
$offset = 0
$query = $this->db->get_where('items', array('id' => $id), $limit, $offset);
Option 2
$this->db->get("items")->row();
class receipt_model extends CI_Model {
public function index(){
$this->db->select('*');
$this->db->from('donor_details');
$this->db->order_by('donor_id','desc');
$query=$this->db->get();
$row=$query->row();
return $row;
}
}
Related
I'm fairly new to Drupal, and I need your help on this issue:
I have built a module on Drupal 7 which makes a database query to extract the name and the email of all users. The code is this:
<?php
/**
*
*/
function myexample_block_info() {
$blocks['myblock'] = array(
'info' => t('My Custom Modue'),
);
return $blocks;
}
function myexample_block_view($delta = '') {
$block = array();
$results = db_select('users','a')
->fields('a', array('name', 'mail'))
->execute();
$header = array(t('NAME'), t('MAIL'));
$rows = array();
foreach ($results as $node) {
$rows[] = array(
$node->name,
$node->mail,
);
}
$block['content'] = theme('table', array('header' => $header, 'rows' => $rows));
return $block;
}
I put the block into "Side-bar first"-Bartik theme. The code works and it retrieves what I want. But the problem with the display. I'm getting the results repeated 3 times:
Results
Why am I getting the results repeated three times. I cant seem to find anything wrong with the code. Could anyone help me please? Thanks in advance.
What are you trying to achieve ? If you are just trying to extract data from the DB this is not the way to go. You should extract data via mysql client directly.
I need to get array MAX ID from column pr_id at my pr_data table. Here's my code what I have tried so far.
public function get_id_max($id) {
$this->db->select_max(array('pr_id' => $id));
$query = $this->db->get('pr_data');
return $query->row_array();
}
Try this:
$this->db->select_max('pr_id');
$this->db->where('pr_id', $id);
$result = $this->db->get('pr_data');
return $query->row_array();
I am looking to except single element from array. My array is:
Array
(
[0] => Array
(
[0] => Array
(
[COUNT(ID)] => 0
)
)
)
I have already use PHP functions basename and array_shift, but they didn't give me proper value. I want only single string COUNT(ID) value.
Here is my function using in cakephp model:
$res = $this->query("select COUNT(ID) from users where Username = '".$Username['Username']."'");
if ($res[0][0]['COUNT(ID)'] >= 1)
{
return false;
}
else
{
return true;
}
I don't need $res[0][0], I need only COUNT[ID]. Is there any easy way to find only COUNT[ID].
If you are using CakePHP, it's good to use model and inbuilt functions to get answer what you want...
$this->loadModel('User'); //If you are in controller
$total = $this->User->find('count', array(
'conditions' => array('Username' => $Username['Username'])
));
You'll get answer in single variable..!!
Your output is produced by code like this
$data = array(
array(
array(
'COUNT(ID)' => 0
)
)
);
You can access its value by calling directly
$data[0][0]['COUNT(ID)']
This could be wrong problem you are solving, as it seems like database query result that should not look like that and could be done with more ease. You should show your original function/problem, that this script is part of.
Let's say you array's name is $myArray, than you can assign the value of $myArray[0][0]['COUNT(ID)'] to $value in the way you usually assign a value: $value = $myArray[0][0]['COUNT(ID)'];.
If you want to delete an index from an array, use unset() like this: unset($myArray[0][0]['COUNT(ID)']). I hope this answers your question.
If you know the exact count of nesting in array you can just access it with indexes
$array[0][0]['COUNT(ID)']
If no, you might want to use the function which will recursively find you the first nested element that is not an array
function getStringFromArray($array) {
if (is_array($array)) {
foreach ($array as $key => $value) {
if (is_array($value)) {
return getStringFromArray($value);
} else {
return $value;
}
}
} else {
throw new Exception("Not an array given");
}
}
If you are sure that array structure will remain same then this could be useful :-
function array_values_recursive($ary)
{
$lst = array();
foreach( array_keys($ary) as $k ){
$v = $ary[$k];
if (is_scalar($v)) {
$lst[] = $v;
} elseif (is_array($v)) {
$lst = array_merge( $lst,
array_values_recursive($v)
);
}
}
return $lst;
}
$arr=array(array(array('COUNT(ID)'=>5)));
$res=array_values_recursive($arr);
echo '<pre>';print_r($res);
output :-
Array
(
[0] => 5
)
You can probably fetch it by associative array to reduce dimension but you can remove index. May be you can use foreach to automatically use indexs.
Try this code:
public $uses = array('User');
$count = $this->User->find('count', array(
'conditions' => array('Username' => $Username['Username'])
));
if ($count >= 1) {
return false;
} else {
return true;
}
You can use following technique for your solution. i did not get you what you want to do with your array but you can try below solution
$arr = Set::extract("/0/COUNT(ID)",$data);
where $data is your input array.
you will get following output
Array
(
[0] => 5
)
you can refer below link
Remove array key from array in cakephp
I have searched around for examples but i am getting an odd result
i wish to have the following occur /pages/1 URL to return from the database the markup column of row 1 of the pages table.
controller
public function index()
{
$id = $this->uri->segment(2);
$content = $this->page->specificMarkup($id);
$this->template->set('nav', 'support');
$this->template->set('content', $content);
$this->template->load('master', 'contact');
}
model
public function specificMarkup($id)
{
$query = $this->db->get_where('pages', $id);
$row = $query->row();
return $row->markup;
}
it works when i specifically set the $id, but now returns a 404 error when i try to use segments, the user guide gives me the impression that this should work.
I will answer my own question for others that run into this issue.
1.
the model needs to be
public function specificMarkup($id)
{
$query = $this->db->get_where('pages', array('id' => $id));
$row = $query->row();
return $row->markup;
}
2.
Their does need to be an entry in the routes.php
$route[ 'pages/(:num)' ] = 'pages/index/$1'
This is so codeigniter knows where to direct the traffic
I currently have index, view, add and edit from my tickets/views and am planning to add another view called current. I want to display only the "Resolved" tickets on that view but have no idea how to do it. I've been trying to figure this out for the past couple of days with no luck. Where should I put the "find" code and what should I include on my tickets/current view code? Here's what I have tried so far:
/controllers/tickets_controller
function current() {
$current = $this->set('tickets', $this->Ticket->find('all', array(
'conditions' => array('Ticket.status' => 'Resolved'),
'order' => array('Ticket.created' => 'desc')
)));
$this->set('tickets', $this->paginate());
}
/views/tickets/current.ctp
<?php
$i = 0;
foreach ($tickets as $ticket):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
This code displays the same as /views/tickets/index.ctp (with all the records from the table).
Thanks,
Lyman
You were almost there. $this->set('foo') in Cake is one way you can pass variables to the view.
What the code below does is set a variable called current the return value of the find method which has a custom condition, which can be accessed from the view. (It's an array in this case; but you can set anything)
You don't need the paginate() here unless you plan to use pagination in this view.
So something like this should do the trick ($curr is a bad variable name but I wasn't feeling inventive. (resolved_tickets would make more sense (why current?))
//controllers/tickets_controller
function current() {
$this->set('current', $this->Ticket->find('all',
array('conditions' => array('Ticket.status' => 'Resolved'),
'order' => array('Ticket.created' => 'desc')
)));
}
/views/tickets/current.ctp
<?php
$i = 0;
// adjust the variable in the foreach
foreach ($current as $curr):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
echo $curr['Ticket']['id']; // example
?>