I have a problem with Kohana database.
Sometimes I have error
ErrorException [ Recoverable Error ]
Argument 1 passed to Kohana_Database_Query_Builder_Select::compile() must be an instance of Database, string given, called in /srv/sites/mysite/www/modules/database/classes/kohana/database/query.php on line 230 and defined
It's happens because in Database:$instances containts string "dances", but should contain array database configurations.
This my config:
<?php defined('SYSPATH') OR die('No direct access allowed.');
return array
(
'default' => array
(
'type' => 'MySQL',
'connection' => array(
'hostname' => 'localhost',
'database' => 'chat',
'username' => 'root',
'password' => 'root',
'persistent' => FALSE,
),
'table_prefix' => '',
'charset' => 'utf8',
'caching' => FALSE,
'profiling' => TRUE
)
);
Maybe somebody had problem like this or could help me?
Any query to DB causes error.
Like this:
Jelly::factory('user', $user->id())
or this:
DB::select('value')->from('storage')->where('name', '=', 'salt')->limit(1)->execute();
or this:
ORM::factory('node')->where('type', '=', 'page-homepage')->find();
I don't know why this error happen. I checked all methods are called and I have not found any mistakes.
I solved this problem by write method instance in class Database
public static function instance($name = NULL, array $config = NULL)
{
if ($name === NULL)
{
// Use the default instance name
$name = Database::$default;
}
if ( ! is_array(Database::$instances))
{
Database::$instances = array();
}
if ( ! isset(Database::$instances[$name]))
{
if ($config === NULL)
{
// Load the configuration for this database
$config = Kohana::$config->load('database')->get($name);
}
if ( ! isset($config['type']))
{
throw new Kohana_Exception('Database type not defined in :name configuration',
array(':name' => $name));
}
// Set the driver class name
$driver = 'Database_'.ucfirst($config['type']);
// Create the database connection instance
new $driver($name, $config);
}
return Database::$instances[$name];
}
I add condition As you can see
if ( ! is_array(Database::$instances))
{
Database::$instances = array();
}
I don't like this, but I have no choise.
My wild guess would be that you seem to be overwriting the compile, quote, quote_column, quote_identifier, quote_table or execute method from Kohana_Database in your code or simply calling ->execute('dances') should trigger this error.
the compile method shouldn't be called directly, it's an internal function that is called from execute()
Any of these functions take $db as the first parameter. Don't pass anything, since you want to use the database set in your config file, without trying to set it manually in your query builder.
Related
In our app, we are handing all error and inserting in tbl_error_log table. But due to some reason it has stopped work and now no error is inserting in error_log table except initialize function error. If error in initialize function then it is working. We are using below code for inserting error.
File path : Vendor/Cakephp/Cakephp/src/Error/BaseErrorhandler.php
protected function _logError($level, $data) {
$ErrorLogTable = TableRegistry::get('tbl_error_log');
$errorlog = $ErrorLogTable->newEntity();
$errorlog->in_user_id = $User['member_id'];
$errorlog->st_email_address = $User['email'];
$errorlog->in_error_no = $data['code'];
$errorlog->st_error_type = $data['error'];
$errorlog->st_error_string = $data['description'];
$errorlog->st_error_file = $data['file'];
$errorlog->in_error_line_no = $data['line'];
$errorlog->dt_error_time = new \DateTime('now');
$errorlog->st_from_ip = $this->getClientIp();
$ErrorLogTable->save($errorlog);
}
I can't speak about your problem with errors only logged from certain code parts, but generally that's not how to do custo logging. Never modify vendor files (unless for testing purposes of course), they will eventually be overwritten when updating the dependencies.
If you want to implement custom logging functionality, then create a custom logger as shown in the docs:
// src/Log/Engine/DatabaseLog.php
namespace App\Log\Engine;
use Cake\Log\Engine\BaseLog;
class DatabaseLog extends BaseLog
{
public function __construct($options = [])
{
parent::__construct($options);
// ...
}
public function log($level, $message, array $context = [])
{
// Write to the database.
}
}
See Cookbook > Logging > Creating Log Adapters
You can use it as the default logger by changing the configuration in your config/app.php file accordingly:
'Log' => [
'debug' => [
'className' => 'Database',
'scopes' => false,
'levels' => ['notice', 'info', 'debug'],
],
'error' => [
'className' => 'Database',
'scopes' => false,
'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
],
// ...
],
I have been searching all over, found a few "solutions" to this, some even made me re-write most of my InputFilter and add a lot of stuff to my Module.php and/or module.config.php... With no luck whatsoever... Just couldn't make it work for me, still got all sort of errors.
I decided to undo everything and start from scratch (the way my code initially looked, before getting to validate form entries against the db) and ask my question here.
I am doing a registration process.
Of course, I need to validate the email address against existing records in my users table (no 2 identical email addresses should be allowed).
Sure, in my database I have that column set to only accept unique values... but I also have to validate it and give the user the appropriate message on form submit, before I actually do anything with the database.
How do I use Db\NoRecordExists (or any other Db validator for that matter)?
What should I further write in my code (add/edit)?
I've pasted all my code below.
The form element I need to add the Db\NoRecordExists validator is 'user_identifier'.
This is my /config/autoload/global.php :
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=my_database_name;host=localhost',
'username' => 'my_user',
'password' => 'my_password',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
This is my Registration form (/module/User/src/User/Form/RegisterForm.php) :
namespace User\Form;
use Zend\Form\Form;
class RegisterForm extends Form {
public function __construct() {
parent::__construct('register');
$this->setHydrator(new \Zend\Stdlib\Hydrator\Reflection());
$this->setObject(new \User\Entity\Users());
$this->setAttributes(array(
// not important for my issue
));
$this->setInputFilter(new \User\Form\RegisterFilter);
// User Identifier
$identifier = new \Zend\Form\Element\Email();
$identifier->setName('user_identifier');
$identifier->setAttributes(array(
'id' => 'user-email',
'placeholder' => 'Email',
'class' => 'form-control'
));
$identifier->setLabel('Your email:');
/*
* Many other fields were here, but to make the sample code
* shorter here, I've only left one of the fields I need to
* validate against the database
*/
$this->add($identifier); // User's email - used for login
// Submit
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Register',
'class' => 'btn btn-primary',
),
));
}
}
And here is my RegisterFilter (/module/User/src/User/Form/RegisterFilter.php) :
namespace User\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Db\Adapter\Adapter;
class RegisterFilter extends InputFilter {
public function __construct() {
// User Identifier (Email)
$this->add(array(
'name' => 'user_identifier',
'required' => true,
'filters' => array(
array('name' => 'StringTrim'),
),
'validators' => array(
/*
* Some validators here (NotEmpty, EmailAddress)
*/
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'users',
'field' => 'user_identifier',
/*
* 'adapter' => had many examples for what to put here, like:
* \Zend\Db\TableGateway\Feature\GlobalAdapterFeature::getStaticAdapter()
* and for that I also had to put:
'Zend\Db\Adapter\Adapter' => function ($sm) {
$adapterFactory = new Zend\Db\Adapter\AdapterServiceFactory();
$adapter = $adapterFactory->createService($sm);
\Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($adapter);
return $adapter;
}
* in my /config/autoload/global.php (and can't remember anything else) BUT, while
* following the example to the letter, I still got errors (like "no static adapter blah-blah - can't remember) and didn't work
* and so on... followed quite a few different examples/methods, rewrote/added many lines in my code
* (in the Model and/or Controller and/or Module.php) but still couldn't make things work for me.
*/
),
),
),
));
/*
* Filters and validators for the rest of the form elements here
* Removed them so I would keep the code focused on my question
*/
}
}
Here's my User module's Module.php (/module/User/Module.php) :
namespace User;
use User\Entity\Users;
use User\Entity\UsersTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
class Module {
public function getAutoloaderConfig() {
// ...
}
public function getConfig() {
// ...
}
public function getViewHelperConfig() {
// ...
}
public function getServiceConfig() {
return array(
'factories' => array(
'User\Entity\UsersTable' => function($sm) {
$tableGateway = $sm->get('UsersTableGateway');
$table = new UsersTable($tableGateway);
return $table;
},
'UsersTableGateway' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Users());
return new TableGateway('users', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
Here is my model (/module/User/src/User/Entity/Users.php):
namespace User\Entity;
class Users {
public $user_id;
public $other_id;
public $user_identifier;
public $user_credential;
public $user_type;
public $user_alias;
public $active;
public $enabled;
public $token;
public $created;
public function exchangeArray($data) {
$this->user_id = (isset($data['user_id'])) ? $data['user_id'] : null;
$this->other_id = (isset($data['other_id'])) ? $data['other_id'] : 0;
$this->user_identifier = (isset($data['user_identifier'])) ? $data['user_identifier'] : 'what?';
$this->user_credential = (isset($data['user_credential'])) ? md5($data['user_credential']) : 'not-possible';
$this->user_type = (isset($data['user_type'])) ? $data['user_type'] : 'client';
$this->user_alias = (isset($data['user_alias'])) ? $data['user_alias'] : 'Anonymus';
$this->active = (isset($data['active'])) ? $data['active'] : 0;
$this->enabled = (isset($data['enabled'])) ? $data['enabled'] : 1;
$this->token = (isset($data['token'])) ? $data['token'] : 'no-token';
$this->created = (isset($data['created'])) ? $data['created'] : date('Y-m-d h:m:s', time());
}
public function getArrayCopy() {
return get_object_vars($this);
}
}
and the TableGateway (/module/User/src/User/Entity/UsersTable.php) :
namespace User\Entity;
use Zend\Db\TableGateway\TableGateway;
class UsersTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
/*
* fetchAll(), getUserById(), deleteUser() etc.
* Different methods here...
*/
public function saveUser(Users $user) {
$data = array(
'user_id' => $user->user_id,
'other_id' => $user->other_id,
'user_identifier' => $user->user_identifier,
'user_credential' => $user->user_credential,
'user_type' => $user->user_type,
'user_alias' => $user->user_alias,
'active' => $user->active,
'enabled' => $user->enabled,
'token' => $user->token,
'created' => $user->created
);
$user_id = (int)$user->user_id;
if ($user_id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getUser($user_id)) {
$this->tableGateway->update($data, array('user_id' => $user_id));
} else {
throw new \Exception("User with id {$user_id} does not exist");
}
}
}
}
And last, but not least, here's my controller (/module/User/src/User/Controller/IndexController.php) :
namespace User\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use User\Entity\Users;
class IndexController extends AbstractActionController {
public function registerAction() {
$registerForm = new \User\Form\RegisterForm;
if ($this->getRequest()->isPost()) {
// Form processing
$formData = $this->getRequest()->getPost();
$registerForm->setData($formData);
if ($registerForm->isValid()) {
// Insert into DB here
$user = new Users();
$user->exchangeArray($formData->user);
$this->getUsersTable()->saveUser($user);
}
return new ViewModel(array(
'form' => $registerForm,
));
} else {
return new ViewModel(array(
'form' => $registerForm,
));
}
}
/*
* Other methods go here
* login, logout, editAccount, emailConfirmation
* etc.
*/
public function getUsersTable() {
if (!$this->usersTable) {
$sm = $this->getServiceLocator();
$this->usersTable = $sm->get('User\Entity\UsersTable');
}
return $this->usersTable;
}
}
First of all I feel the need to shout here:
If in my /config/autoload/global.php I have set up my database connection, why on earth should I ever, in any other place in the application, speciffy anything (else) regarding the database, except maybe just the table I want to use?
Why do I have to mess around with setters and getters and factories and service manager and so on at the module level (sometimes even in the controller) and fatten the code so much? And as far as I can see from all sorts of examples (from which I got to write the code in getServiceConfig() in my Module.php), I need to do that for every entity. wtf? This really sucks! Big time!
Then, if I work with #n tables in a controller, I have to have #n functions like "public function getUsersTable() {}"? And #n factories like 'User\Entity\UsersTable' in my getServiceConfig() in Module.php? That's crap! Is this the best way to go? Or am I just unlucky and keep finding the worst examples possible while learning zf2? Why should there be a getTableNameTable() function in my controller? Isn't the Model that should worry about what table I'm talking about? Since every model is designed for one specific table? Like in zf1, where I would just have "protected $_name = 'users';" in my model and that was all I needed.
Why aren't those connection settings "magically" (simply) available ANYWHERE in my application, like in zf1? Why else am I putting that in the config for? I really don't understand why do I need all that in the getServiceConfig() in my Module.php and how could I avoid that?
Things seamed more compact in zf1. In zf2, most of the time I have no ideea whatsoever of what I'm doing, I copy snipets and prey on form submit or F5 that they work right out of the box and I get no errors. I should also probably mention that I don't have a strong understanding of OOP, I'm just a newb trying to learn zf2 (after using zf1 for 2 projects that had a lot to do with database, content administration, ajax, work with facebook api, google maps). With zf1, even if I bearly had an ideea about OOP, I still could do whatever I needed to do. In zf2, it seams there are 1000 ways right out of the box to do each one thing. Almost every time I'm looking for a solution to some problem I ran into, I find many examples... but most of the time, no example has the base code similar to mine to build upon, so I have to rewrite a lot (because I can't adapt, I'm a newb and if I adapt what I find, I immediately get errors, which I sometimes get even if I rewrite accordingly to the exampled I find).
So, what I am asking is:
In my code, pasted above, what should I add/modiffy in order to make that validation against the database? Because, right now, I get "No database adapter present" <em>sure I do</em>
This probably goes beyond the initial scope of this post, BUT how can I avoid so much code and configuration spreading all over the place? I don't want to have to speciffy anything regarding the database connection all over my application, it really should be done in one place and all other modules and entities and controllers should know all there is to know about the database (without telling them where to look in every controller/model, they should simply know that from the config), anything else they would need to know at Model(Entity)/Controller level should just be the table I want to work with, I shouldn't need to repeat myself and keep saying all over the place that "this is my adapter, there - get it from >here<" - that's crap) stop messing with getters and setters and factories and service manager and "make this from here available to that over there" etc. I shouldn't speciffy an adapter in my InputFilters or anywhere except the global/local.php. All that I should tell the validator in the input filter is the table and column to validate against, isn't this more natural?
I did this by passing the adapter to my interface:
Controller code:
if ($request->isPost()) {
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$admins = new Admins($dbAdapter);
.
.
.
}
My interface code:
class Admins implements InputFilterAwareInterface
{
public $id;
public $first_name;
public $last_name;
/* etc */
private $gatewayAdapter;
public function __construct($dbAdapter = null) {
$this->gatewayAdapter = $dbAdapter;
}
/* etc*/
public function getInputFilter() {
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$factory = new InputFactory();
$inputFilter->add($factory->createInput(array(
'name' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
/* etc */
$inputFilter->add($factory->createInput(array(
'name' => 'email',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array('name' => 'NotEmpty',),
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'admins',
'field' => 'email',
'adapter' => $this->gatewayAdapter
),
),
),
)));
/* etc */
}
/* etc */
}
Using cakephp 2.3.8 I am attempting to setup a connection to a custom couchbase datasource I have made within another datasource. The datasource I am attempting to load functions properly on the rest of the site when being loaded via a model. I want to use the connection manager to load this datasource. This is what I have so far:
database.php file:
public $queriesCB = array(
'datasource' => 'CouchbaseSource',
'username' => 'queries',
'password' => '',
'bucket' => 'queries',
'prefix' => 'q_',
'expiry' => '1814400', //3 Weeks
'autoConnect' => true,
'database' => NULL ,
'persistent' => false
);
Within my other datasource trying to load couchbase datasource
$db = ConnectionManager::getDataSource("queriesCB");
When I debug $db I get this:
object(CouchbaseSource) {
description => 'Couchbase DataSource'
conObject => object(Couchbase) {
[private] _handle => resource
}
config => array(
'password' => '*****',
'database' => '*****',
'prefix' => '*****',
'datasource' => 'CouchbaseSource',
'username' => 'queries',
'bucket' => 'queries',
'expiry' => '1814400',
'autoConnect' => true,
'persistent' => false
)
prefix => 'q__'
connected => false
cacheSources => true
configKeyName => 'queriesCB'
[protected] _baseConfig => array()
[protected] _descriptions => array()
[protected] _sources => null
[protected] _transactionStarted => false
}
Now when I try to call this I get a error:
$db = ConnectionManager::getDataSource("queriesCB");
$db->Get('test');
Error: Call to undefined method CouchbaseSource::Get().
This is a custom method, the datasource is all custom to work best with couchbase and the Get method does function properly. How am I setting up this connection wrong in cakephp?
Edit:
I just tested it with the default database config to a mysql database, it fails as well. The question now would be what would be the best way to initialize a new datasource? should I have to load a model with that datasource attached? Example: have a couchbase model with the datasource as couchbase?
Edit: Here is some of the datasource
class CouchbaseSource extends DataSource {
public $description = 'Couchbase DataSource';
public $conObject = NULL;
public $config = NULL;
public $prefix = NULL;
public function __construct($config = array()){
// If no configuration is set we use the default
$this->config = $config;
// Setup the cache string that is used when building the string
$this->prefix = (isset($this->config['prefix']) ? $this->config['prefix']."_" : "");
if ($this->config['autoConnect']) {
$this->connect();
}
}
public function connect() {
if ($this->conObject !== true) {
try {
$this->conObject = new Couchbase("127.0.0.1:8091", $this->config['username'], $this->config['password'], $this->config['bucket'], $this->config['persistent']);
} catch (Exception $e) {
throw new MissingConnectionException(array('class' => $e->getMessage()));
}
}
return $this->conObject;
}
public function query($method, $params, $object) {
// If not connected... reconnect!
if(!$this->conObject) {
$this->connect();
}
$apiMethod = $this->__methodToClass($method);
if (!method_exists($this, $apiMethod)) {
throw new NotFoundException("Class '{$apiMethod}' was not found");
} else {
return call_user_func_array(array($this, $apiMethod), $params);
}
}
private function __methodToClass($method) {
return 'CB' . strtolower(Inflector::camelize($method));
}
public function describe(&$Model) {
return $this->description;
}
/////////////////////////////////////////////////
// Query Methods
/////////////////////////////////////////////////
public function CBadd($key = NULL, $value = NULL, $expiry = NULL, $persisto = NULL, $replicateto = NULL) {
return $this->conObject->add($key, $value, $expiry, $persisto, $replicateto);
}
The solution is to directly call the query method from the couchbasesource. Given the way that I setup the datasource, unlike linking it through a model, the query information was not automatically passed. My go around was to simple use this.
App::uses('ConnectionManager', 'Model');
$db = ConnectionManager::getDataSource("queriesCB");
debug($db->query('Get', array('test')));
How can I create a custom Rule-Action which will successfully save a value as a replacement pattern for use in the other actions?
I got some very good help here on retrieving Product-Display information from a Product-Order.
As I said, the linked answer helped a great deal but the returned path data for the Product-Display comes back in the http://www.mysite/node/77 format. However, I really just need the numeric value only so I can load the node by performing a Fetch entity by id action supplying the numeric value and publishing the Product-Display node etc.
So, I implemented a custom action which will take the Product-Display URL(node/77) and return 77.
I copied the Fetch entity by id code and modified it so my returned numeric value can be saved and used in other Actions. The code is below:
function my_custom_action_info(){
$actions['publish_product_display_node'] = array(
'label' => t('Fetch product-display id'),
'parameter' => array(
'type' => array(
'type' => 'uri',
'label' => t('My Action'),
'options list' => 'rules_entity_action_type_options2',
'description' => t('Specifies the product-display url.'),
),
),
'provides' => array(
'entity_fetched' => array('type' => 'integer', 'label' => t('Fetched entity')),
),
'group' => t('Entities'),
'access callback' => 'rules_entity_action_access',
);
return $actions;
}
function publish_product_display_node($path = null){
$parts = explode('node/', $path);
return $parts[1];
}
function rules_entity_action_type_options2($element, $name = NULL) {
// We allow calling this function with just the element name too. That way
// we ease manual re-use.
$name = is_object($element) ? $element->getElementName() : $element;
return ($name == 'entity_create') ? rules_entity_type_options2('create') : rules_entity_type_options2();
}
function rules_entity_type_options2($key = NULL) {
$info = entity_get_info();
$types = array();
foreach ($info as $type => $entity_info) {
if (empty($entity_info['configuration']) && empty($entity_info['exportable'])) {
if (!isset($key) || entity_type_supports($type, $key)) {
$types[$type] = $entity_info['label'];
}
}
}
return $types;
}
function rules_action_entity_createfetch_access2(RulesAbstractPlugin $element) {
$op = $element->getElementName() == 'entity_create' ? 'create' : 'view';
return entity_access($op, $element->settings['type']);
}
As I said I copied the modified code so I don't claim to thoroughly understand all the functions aside from publish_product_display_node.
My code modifications work as far as setting the Product-Display URL token as the argument and also setting an entity variable label(Display NID) and value(display_nid).
The problem is when I check display_nid in newly created actions, the value is empty.
I need help figuring out the how to successfully save my entity value so I can use it in following Actions.
in the function publish_product_display_node, can you verify that you don't need to be returning $parts[0], instead of $[parts[1]?
It's just that Drupal paths are frequently in the form 'node/7' or 'taxonomy/term/6', and if you explode with 'node/' as the separator, you'd only have a single value which would start at index 0 for nodes...
So, just wondering if that would solve your issue...
I'm upgrading an application that presently runs on ZendFramework1(ZF1) to ZendFramework2(ZF2). I'm having trouble getting DB results to return from the ZF2 connection.
In ZF1 this test works perfectly:
$db = Zend_Db::factory('Pdo_Mssql', array(
'host' => 'ServerNameFromFreeTdsConfig',
'charset' => 'UTF-8',
'username' => 'myUsername',
'password' => 'myPassword',
'dbname' => 'database_name',
'pdoType' => 'dblib'
));
$stmt = $db->prepare("select * from Products");
$stmt->execute();
$result = $stmt->fetchAll();
$stmt->closeCursor();
However, I've been trying this in ZF2 but I'm not really getting anywhere. In my config\autoload\global.php I have:
return array(
'db' => array(
'host' => 'ServerNameFromFreeTdsConfig',
'charset' => 'UTF-8',
'dbname' => 'database_name',
'username' => 'myUsername',
'password' => 'myPassword',
'driver' => 'pdo',
'pdodriver' => 'dblib',
),
);
And in the Module.php file:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$config = $e->getApplication()->getServiceManager()->get('Configuration');
$dbAdapter = new Adapter($config['db'], new SqlServer());
GlobalAdapterFeature::setStaticAdapter($dbAdapter);
}
Then in the Model\Products.php
class Products extends AbstractTableGateway
{
protected $table;
protected $featureSet;
public function __construct($table = 'Products') {
$this->table = $table;
$this->featureSet = new FeatureSet();
$this->featureSet->addFeature(new GlobalAdapterFeature());
$this->initialize();
}
//Test the connection.
public function getProducts() {
$result = $this->getAdapter()->query("select * from Products", Adapter::QUERY_MODE_EXECUTE);
die(var_dump($result));
}
}
It looks like it is connecting because the "var_dump" above returns a ["fieldCount":protected]=> int(7) which is correct (there are 7 columns in that table). However, it is not returning any results.
What might I need to do to get this to work in ZF2? Do I need to somehow extend Zend\Db\Adapter\Adapter using code from the ZF1 Zend_Db_Adapter_Pdo_Mssql.php file? Or is there some simple solution I'm missing?
Thanks for any insight.
I think you dont need to mention the user name and password
resources.db.adapter = "sqlsrv"
resources.db.host = "localhost\SQLEXPRESS"
resources.db.dbname = "DatabaseName"
resources.db.isDefaultTableAdapter = true
resources.db.driver_options.ReturnDatesAsStrings = true
I ended up writing my own Adapter adopted from the Zend Framework 1 adapter I had working there. If someone comes across this post looking for a solution to the same problem and would like a copy of the code I transposed, let me know. There is quite a lot of code or I'd post it here.