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
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'm working on an edit method. After saving data, an email is sent out with the changes made during the edit. Everything works except for one infuriating but crucial bug. Here it is distilled down very simply:
$data = $this->SupportTicket->readForView($st_id);
$this->SupportTicket->id = $st_id;
if ($this->SupportTicket->save($this->request->data)) {
//call custom model method to pull view data
$data = $this->SupportTicket->readForView($st_id);
//do something with this data
}
The issue is that $data comes out with the pre-save data. So what I then try to do with the new data doesn't work.
I can't just use $this->request->data because it doesn't have the full data that I want in it.
The save does however work. If I refresh the view method for the same record, it shows as updated. So it's saving, but when I do the find after saving it is giving me old data.
Any ideas?
Update: it doesn't happen with findById($st_id) so it must be something to do with my custom method. Code:
public function readForView($id)
{
$data = $this->find('first', array(
'conditions' => array(
'SupportTicket.id' => $id
),
'contain' => array(
'User',
'Owner'
)
));
if (empty($data)) {
throw new notFoundException('Ticket not found');
}
$data['SupportTicket']['type_long'] = $this->getLongType($data['SupportTicket']['type']);
$data['SupportTicket']['status_long'] = $this->getLongStatus($data['SupportTicket']['status']);
$data['SupportTicket']['name'] = 'Support Ticket #' . $data['SupportTicket']['id'] . ' - ' . $data['SupportTicket']['title'];
return $data;
}
Copying the code from this method into the Controller gives the same result.
I've found this helpful: https://edivad.wordpress.com/2008/04/15/cakephp-disable-model-queries-caching/
By model:
class Project extends AppModel {
var $cacheQueries = false;
...
By function:
function someFunction {
$this->Model->cacheQueries = false;
...
try using last Insert ID
$id=$this->getLastInsertID();
public function readForView($id)
I am working on cakephp now.Please explain the process of custom mysql query in cake php.
we have to write query by using
$this->Model->query();
and I return this to controller.In controller,i loaded the model in particular function and i called the function and set that function to view like this
$this->set('post',$this->User->get());
is it correct process?please explain the code ...
What query do you want to write this way? It is possible to write nearly all queries using the CakePHP ORM. Using the query building functions of CakePHP is the prefered way of doing it.
All data fetching an manipulation should be done in a model as well. See Separation of Concerns.
Here is a complete model method to fetch an user record based on its id OR slug.
public function view($userId, $options = []) {
$defaults = array(
'contain' => array(),
'conditions' => array(
'OR' => array(
$this->alias . '.' . $this->primaryKey => $userId,
$this->alias . '.slug' => $userId,
),
$this->alias . '.email_verified' => 1
),
);
$result = $this->find('first', Hash::merge($defaults, $options));
if (empty($result)) {
throw new NotFoundException(__d('user_tools', 'User not found!'));
}
return $result;
}
Controller:
public function view($userId = null) {
$this->set('user', $this->User->view($userId);
}
Alternative but NOT preferred mode method to fetch te data
public function view($userId, $options = []) {
$result = $this->query(/* Your query here */);
if (empty($result)) {
throw new NotFoundException(__d('user_tools', 'User not found!'));
}
return $result;
}
Your solution is correct, let me eleborate it in more detail
1st Solution
In your controller
$arrayTemp =array();
$arrayTemp = $this->ModelName->query(' Your Query String ');
$this->set('post',$arrayTemp);
2nd Solution
In your model class
function returnDate(){
return $this->query('Your Query String')
}
In Controller class
$arrayTemp = $this->ModelName->returnDate();
$this->set('post',$arrayTemp);
}
I am trying to avoid creating a view for each AJAX function I am using at my controller. (as i don't manipulate the resulting data in any way and in most cases is just a boolean value)
I am using RequestHandler component at my controller:
var $components = array('RequestHandler');
And I added this in routes.php
Router::parseExtensions('json');
I am trying to make this function to work, but I am getting a null value:
public function test(){
$this->layout = 'ajax';
$result = '1';
$this->set('_serialize', $result);
}
To access to the json version of the function i use this URL finishing in .json to avoid loading any view:
http://localhost/cakephp/demoController/test.json
I have been following the steps from CakePHP documentation:
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#json-and-xml-views
What am I doing wrong? Why don't I get the expecting result and instead I get a null?
Also, if I try to to serialize some array, like this one:
$result = array('demo' => '1');
$this->set('_serialize', $result);
I'm getting this notice:
Notice (8): Undefined index: 1 [CORE\Cake\View\JsonView.php, line 89]Code Context $data = array();
foreach ($serialize as $key) {
$data[$key] = $this->viewVars[$key];$view = null
$layout = null
$serialize = array(
'demo' => '1'
)
$data = array()
$key = '1'JsonView::render() - CORE\Cake\View\JsonView.php, line 89
Controller::render() - CORE\Cake\Controller\Controller.php, line 957
Dispatcher::_invoke() - CORE\Cake\Routing\Dispatcher.php, line 193
Dispatcher::dispatch() - CORE\Cake\Routing\Dispatcher.php, line 161
require - APP\webroot\index.php, line 92
[main] - ROOT\index.php, line 42{"1":null}
As far as I understand the documentation you have to specify a view variable and then refer to this variable when you use the _serialize key. This means your snippet would look like:
$result = '1';
$this->set('theResult', $result);
$this->set('_serialize', array('theResult'));
I don't have the .json extension in the URL and the Router::parseExtensions('json'); line in my routes.php file, so the #dhofstet's answer did not work for me.
My solution was to add the renderAs() call:
public $components = array('RequestHandler');
public function my_ajax_action() {
// do something
$result = '1';
$this->set('result', $result);
$this->set('_serialize', array('result'));
$this->RequestHandler->renderAs($this, 'json');
}
You could create an element and render it.
function test() {
$this->autoRender = false;
$result = array('demo' => '1');
$this->set(compact('result'));
$this->set('_serialize', array('result'));
$this->render(DS.'Elements'.DS.'element_name');
}
See docs
The simplest way is this. Works well for me.
public function fun() {
$this->autoRender = false;
$this->request->onlyAllow('ajax');
$result = array('data1' => 'hello', 'data2' => 'world');
return json_encode($result);
}
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;
}
}