CakePHP 2.1.x - Run a query without any models in AppController - cakephp

I am trying to run a query in AppController on a table that has no Model associated with it. I don't want to use a Model cause this query would fire on every request and I guess using a Model would make it a bit slower.
I found out in one forum that this can be achieved with the following code in CakePHP 1.3
$db = ConnectionManager::getInstance();
$conn = $db->getDataSource('default');
$conn->rawQuery($some_sql);
But this is not working in CakePHP 2.1.3.
Any help would be appreciated.
Thanks :)

The getDataSource() method is static in CakePHP 2.x, so you should be able to use:
$db = ConnectionManager::getDataSource('default');
$db->rawQuery($some_sql);

you should run this way
App::uses('ConnectionManager', 'Model');
$db = ConnectionManager::getDataSource('default');
if (!$db->isConnected()) {
$this->Session->setFlash(__('Could not connect to database.'), 'default', array('class' => 'error'));
} else {
$db->rawQuery($some_sql);
}

rawQuery will not return data, use $db->query instead.
$db = ConnectionManager::getDataSource('default');
$data = $db->query($some_sql);

Related

Query limitation in DBO (Joomla 3.8.1)

I use JDatabaseDriver for interaction with database.
The next code I took from official Joomla Documentation.
Documentation
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query
->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')))
->from($db->quoteName('#__user_profiles'))
->setLimit('10');
Look at the last row in code above.
The setlimit method is no exist in JDatabaseDriver class but it is declared in class - JDatabaseQueryMysqli.
Don't I understand the logic or there is some mistake?
In Latest Joomla 3.8.1 setLIMIT does not work properly. You may go for alternative methods like
$query->setQuery($query,start,offset);

get validationDefault from model in CakePHP3

I try to make a JsValidate helper, then I need access to validationDefault wrote on my Models table.php, how I can access?
I try
$model = TableRegistry::get($model);
$rules = $model->validationDefault();
but don't work.
I use CakePHP 3.0 ( PHP 5.5 )
You get the validation object by doing:
$rules = $table->validator('default');

Cakephp: Print a comment after queries in Sql log

I'm using CakePHP 2.3 with the debug kit plugin and I need print a commentary after each Sql query in my logs. Is it possible modify it?
To solve the problem, I created an instance of Mysql in Model/Datasource called DboCustomSource. Here I have overwritten the function execute of DboSource to modify the variable $sql.
App::uses('Mysql', 'Model/Datasource/Database');
class DboCustomSource extends Mysql{
public function execute($sql, $options = array(), $params = array()){
$sql .= 'comment';
return parent::execute($sql, $options, $params);
}
}
It's necessary to modify datasource in database's configuration: 'datasource' => 'DboCustomSource'.

Calling $this->model->create() crashes in controller in cakephp

I am having a problem using the create() method in the cakephp. I have the following code and when I run it in debug it just resumes the program when I try to step through it after the create line.
$this->CompanyDeviceQuestionConcern->create();
$this->CompanyDeviceQuestionConcern->set('source_company_id', $company_id);
$this->CompanyDeviceQuestionConcern->set('user_id', $user['id']);
$this->CompanyDeviceQuestionConcern->set('create_date', date('Y-m-d H:i:s'));
$this->CompanyDeviceQuestionConcern->set('modified_date', date('Y-m-d H:i:s'));
Does anyone know why it crashes when I run the first line?
I am not sure but i think your database refuses the create action because of limitations of some fields(like NOT NULL).
There is a workaround for this:
$newData = array(
'id' => NULL,
'source_company_id' => $company_id,
'user_id' => $user['id'],
'create_date' => date('Y-m-d H:i:s'),
'modified_date' => date('Y-m-d H:i:s')
);
$this->CompanyDeviceQuestionConcern->save($newData);
I found the silly mistake. I forgot to include the model in $uses variable in the class at the top. It is rather inconvenient that it doesn't show any type of error however.
Here is what I added to fix it.
class ReviewsController extends AppController {
var $uses = array('Question', 'CompanyTemplateGroupQuestionConcern');
Also if anyone wants any more information on how to uses works you can look here
http://book.cakephp.org/2.0/en/core-utility-libraries/app.html

Trying to write a simple Joomla plugin

Please help, this is my first plugin I'm writing and I'm completely lost. I'm trying to write and update information in a table in a joomla database using my custom giveBadge() function. The functions receives two different variables, the first variable is the $userID and the second one is the digit 300 which I pass at the bottom of the class using giveBadge(300). At the same comparing the $userID in the Joomla database to ensure that the number 300 is given to the current user logged in the Joomla site.
Thanks in advance.
<?php
defined('JPATH_BASE') or die;
class plgUserBadge extends JPlugin
{
public function onUserLogin () {
$user =& JFactory::getUser();
$userID =& user->userID;
return $userID;
}
public function giveBadge ($userID, &$badgeID) {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Fields to update.
$fields = array(
'profile_value=\'Updating custom message for user 1001.\'',
'ordering=2');
// Conditions for which records should be updated.
$conditions = array(
'user_id='.$userID,
'profile_key=\'custom.message\'');
$query->update($db->quoteName('#__user_badges'))->set($fields)->where($conditions);
$db->setQuery($query);
try {
$result = $db->query();
} catch (Exception $e) {
// Catch the error.
}es = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1);
}
}
giveBadge(300); //attaches to $badgeID
?>
Here is not going well with your code:
You can drop the assign by reference in all your code (&) - you really don't need it, in 99% of the cases.
Use an IDE (for example Eclipse with PDT). At the top of your code you have & user->userID; Any IDE will spot your error and also other things in your code.
Study existing plugins to understand how they work. Here is also the documentation on plugins.
The method onUserLogin() will automatically be called by Joomla when the specific event is triggered (when your plugin is activated). Check with a die("My plugin was called") to see if your plugin is really called
inside onUserLogin() you do all your business logic. You are not supposed to return something, just return true. Right now your method does absolutely nothing. But you can call $this->giveBadge() to move the logic to another method.

Resources