I've applied a couple of minor changes to the database structure for my app, adding new columns to a table called Plots. This is one of the migrations -
declare(strict_types=1);
use Migrations\AbstractMigration;
class AddGarageToPlots extends AbstractMigration
{
public function change()
{
$table = $this->table('plots');
$table->addColumn('garage', 'string', [
'default' => null,
'limit' => 255,
'null' => true,
]);
$table->update();
}
}
When I apply the migration it seems to run fine: there are no errors and I can see the new column in the database if I connect directly to it but when I try to access data in the new field in a view using, for example, <?= $plot->garage ?> it consistently returns null even though I have populated this field via the direct connection.
Is there something else I need to do that I'm missing here or is there some way I can check that the migration has worked properly like a schema file somewhere?
Found the answer to my own question by reading slightly further in the documentation - migrations and deployment.
I needed to run bin/cake schema_cache clear
I am using ef-core 2.1 with MSSQL, in OnModelCreating I use the following which auto populates a created field correctly:
modelBuilder
.Entity<MyModel>()
.Property(e => e.Created)
.HasDefaultValueSql("GETUTCDATE()")
.ValueGeneratedOnAdd()
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
Additionally, I want to populate (and update thereafter) another field as follows:
modelBuilder
.Entity<MyModel>()
.Property(e => e.Modified)
.HasDefaultValueSql("GETUTCDATE()")
.ValueGeneratedOnUpdate()
.Metadata.ValueGenerated = ValueGenerated.OnUpdate;
However, this has no effect. In reading value-generated-on-add-or-update it is not clear to me if no facility exists to support this and a trigger is the only option or I simply have the configuration wrong.
The fluent method calls appear to support this, anyone know what I am doing wrong?
Hmm, I am not real familiar with what you are trying with .Metadata.ValueGenerated, however, I am doing something very similar in my project with success (note that my db is MySQL).
Maybe try like below.
modelBuilder
.Entity<MyModel>()
.Property(e => e.Modified)
.HasDefaultValueSql("GETUTCDATE()")
.ValueGeneratedOnAddOrUpdate();
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);
I have a search engine which calls a Cakephp action and receives which model the engine should search in eg. "Projects". The variable is called $data_type;
Right now I use this to check if the model exists:
// Check if Table really exists
if(!TableRegistry::get($data_type)){
// Send error response to view
$response = [
'success' => false,
'error' => 'Data type does not exist'
];
$this->set('response', $response);
return;
}
I'm not sure I'm doing it the right or the safest way to check if a model exists, because I don't know if the TableRegistry::get() function is vulnerable to SQL injection behind the scenes.
I also found that inputing an empty string to the get() function doesn't need in a false result??? Is there a safe solution I can implement that will solve my problem?
TableRegistry::get() is not safe to use with user input
First things first. It's probably rather complicated to inject dangerous SQL via TableRegistry::get(), but not impossible, as the alias passed in the first argument will be used as the database table name in case an auto/generic-table instance is created. However the schema lookup will most likely fail before anything else, also the name will be subject to inflection, specifically underscore and lowercase inflection, so an injection attempt like
Foo; DELETE * FROM Bar;
would end up as:
foo;d_e_l_e_t_e*f_r_o_m_bar;
This would break things as it's invalid SQL, but it won't cause further harm. The bottom line however is that TableRegistry::get() cannot be regarded as safe to use with user input!
The class of the returned instance indicates a table class' existence
TableRegistry::get() looks up and instantiates possible existing table classes for the given alias, and if that fails, it will create a so called auto/generic-table, which is an instance of \Cake\ORM\Table instead of an instance of a concrete subclass thereof.
So you could check the return value against \Cake\ORM\Table to figure whether you've retrieved an instance of an actual existing table class:
$table = TableRegistry::get($data_type);
if (get_class($table) === \Cake\ORM\Table::class) {
// not an existing table class
// ...
}
Use a whitelist
That being said, unless you're working on some kind of administration tool that explicitly needs to be able to access to all tables, the proper thing do would be to use some sort of whitelisting, as having users arbitrarily look up any tables they want could be a security risk:
$whitelist = [
'Projects',
'...'
];
if (in_array($data_type, $whitelist, true) !== true) {
// not in the whitelist, access prohibited
// ...
}
Ideally you'd go even further and apply similar restrictions to the columns that can be looked up.
You may want to checkout https://github.com/FriendsOfCake/awesome-cakephp#search for some ready made search plugins.
I am having trouble with my cakePHP and wondering if anyone else has experienced this. I am trying to setup a User object. I create the Model:
class User extends AppModel
{
}
I create the controller:
class UsersController extends AppController
{
function view($id = null) {
$this->User->id = $id;
$this->set('users', $this->User->read());
}
}
and I go to the view page. However, I am not getting what the cake documentation says I should be getting. I am getting:
Array
(
[0] => Array
(
[id] => 3
[FirstName] => 1
[LastName] => 1
)
)
when what I am expecting to see is
Array
(
[User] => Array
(
[id] => 3
[FirstName] => 1
[LastName] => 1
)
)
Also when I do a $this->User->find('all'); I get back an array like so:
Array
(
[0] => Array ([0] => Array (/*stuff here*/))
[1] => Array ([0] => Array (/*stuff here*/))
[2] => Array ([0] => Array (/*stuff here*/))
)
I have tried changing the name to Myuser (including the database table, controller, model, etc) and still have the same results, so I don't think it's related to a reserved keyword.
Has anyone run into this or, more importantly, does anyone have a clue how I might fix it? Thanks.
EDIT:
I am using cake version 2.0.6. I am using a MySQL 5.0.92 database. I just have tried setting the name variable and it did not change my results.
After an ENTIRE DAY of troubleshooting, I finally was able to solve it.
The cause is definitely an outdated pdo_mysql.so library. This is located in /usr/local/lib/php/extensions/(latest directory)/pdo_mysql.so
The table name being returned in getColumnMeta was only added in a certain version due to this function request:
https://bugs.php.net/41416/
Now, the problem is, in some web hosts, PHP needs to be compiled with Easy Apache. Mine had to go through that as well just in order to enable PDO (it was initially disabled). But the problem is, for some reason, Easy Apache is downloading some obsolete source code everytime it runs. Running yum or installing any RPMs don't help either.
So here is what I did:
- I downloaded the latest PHP sources from the PHP site, extracted the tarball
- I ran Easy Apache, did a recompilation, and very quickly went to the console to watch it redownload the outdated PHP sources
- When the PHP sources have reappeared, I very quickly replaced the entire ext/pdo_mysql directory with the latest sources
- Easy Apache will compile httpd first, so you have some time to do the above step
- After the build is done, reboot.
- To check if your version of pdo_mysql.so supports the table name, execute this command:
strings -f pdo_mysql.so | grep ': table'
- There should be an entry there. The old version doesn't.
- By the way, I noticed that there are more copied of the pdo_mysql.so in /usr/lib/php/modules and /usr/lib/php/extensions, but it seems that the one in /usr/local is the one that is active. Nevertheless, I update all copies manually
NOTE: if you just try to update the pdo_mysql.so file, it will not work. You will get a segmentation fault, and the pages will render nothing. You need to recompile PHP using the above steps.
I hope this will help other people who will come across this bug.
Be sure your table is named users and include the association explicitly
class User extends AppModel {
public $name = 'User';
public $useTable = 'users';
...
You need to set the $uses variable to associate the User model with the controller if you are using any additional models. Adding it explicitly even if there's just one will not hurt either...
for example
class UsersController extends AppController {
//Controller Name
public $name = 'Users';
//DB Config for desired connection
public $useDbConfig = 'test';
// Array of associated models
public $uses = array('Store','User');
//Array of Helpers used by Controller Views
public $helpers = array('Html', 'Form');
...
Also, check to be sure there are no edits in AppModel or AppController which may be accidentally contributing to the interactions here... You may also consider dumping the value of the $uses to see what's there.
Finally found out that the reason for it has to do with a function called PDOStatement::getColumnMeta. This gets called on the queries that cakePHP runs is used by the framework to get the column name, column type, and table name. However, for whatever reason, on the webhost I currently have, this function does not return the table name so cakePHP defaults to creating the array with a 0 index rather than a table name index.
$column = $results->getColumnMeta($index);
if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
$this->map[$index++] = array($column['table'], $column['name'], $type);
} else {
$this->map[$index++] = array(0, $column['name'], $type);
}
still not sure how to fix it yet, but this is definitely why it is happening.
Yes, you are right. beastmaster
The reason why is that u using old version of PDO driver which has been been deprecated. the PDOStatement::getColumnMeta does not show [table]=name in old version
So solution here download new version of PHP which has build-in PDO. DO NOT INSTALL PDO VIA PECL coz u getting old version of PDO extension. and using
<?php phpinfo ?>
to check if it is installed properly. so u can use native PDO driver coming with PHP rather than use extension PDO driver.
By the way, Thank you for point out the problem.
I have just faced the problem. The cause was not an outdated pdo_mysql.so library.
If you use cakephp 2.3.x and make sure to use PHP 5.2.8 or greater, you should check whether the pdo_mysql extension is enabled or disabled.
You can echo phpinfo() to check it.
Note: the pdo_mysql extension is only enabled if you see "PDO Driver for MySQL enabled", otherwise it is disabled.