Getting Statement couldn't be produced with sql in zend2? - php

this is my function in my model:
public function user_login($getData,$session_id){ // manage the user's login
$email = $getData['login_email'];
$password = $getData['login_password'];
$select = $this->adapter->query("select count(*) as counter from users where email = '$email' and password = '".md5($password)."'");
$results = $select->execute();
if ($results->current()['counter'] == 1 ){
$update = $this->adapter->query("update users set session_id = '".$session_id."' where email = '".$email."'");
$update_session = $update->execute();
return 1;
}else{
return 0;
}
}
When I executed the count query it works and im also using this method to get values from queries or to insert data in db. but now i want to do a simple update, which does not work for some reason. I don't know why ? why i'm getting this message ?
UPDATE: this is the content of the Module.php file from my module name folder:
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getServiceConfig() {
return array(
'factories' => array(
'Application\Model\UsersTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new Model\UsersTable($dbAdapter);
return $table;
},
),
);
}
}

Had the same issue, found solution here.
Probably unbuffered query?
$statement = $adapter->query("SELECT ...");
$result = $statement->execute();
$result->buffer();
// validate your result

Related

zf2 tablegateway select columns with join table

I have this code (which works fine):
Class SsoRequserTable
public function fetchAll()
{
$select = new Select();
$select->from("sso_requser");
$select->join('sso_workunit', 'sso_workunit.sso_workunit_id = sso_requser.sso_workunit_id', array("unitname"), 'left');
echo $select->getSqlString();
$result = $this->tableGateway->selectWith($select);
return $result;
}
class SsoRequser
class SsoRequser{
public $sso_requser_id;
public $firstname;
public $lastname;
public $fullname;
public $sso_workunit_id;
public function exchangeArray($data){
$this->sso_requser_id = (!empty($data['sso_requser_id'])) ? $data['sso_requser_id'] : null;
$this->firstname = (!empty($data['firstname'])) ? $data['firstname'] : null;
$this->lastname = (!empty($data['lastname'])) ? $data['lastname'] : null;
$this->fullname = (!empty($data['fullname'])) ? $data['fullname'] : null;
$this->sso_workunit_id = (!empty($data['sso_workunit_id'])) ? $data['sso_workunit_id'] : null;
}
}
Module.php
public function getServiceConfig() {
return array(
'invokables' => array(
// 'Aclplugin' => 'Auth\Controller\Plugin\Aclplugin',
),
'factories' => array('SSO\Model\SsoRequserTable' => function($sm) {
$tableGateway = $sm->get('SsoRequserTableGateway');
$table = new SsoRequserTable($tableGateway);
return $table;
},
'SsoRequserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('postgresql_adapter');
$resultSetPrototype = new HydratingResultSet();
$resultSetPrototype->setObjectPrototype(new SsoRequser());
return new TableGateway('sso_requser', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
But I can`t get the sso_workunit columns to work. I have read the Zend Documentation and nothing effectively worked for me. I need name to have an alias "unitname".
And i got the message error "Undefined property: SSO\Model\Entity\SsoRequser::$unitname "
Whether I should add unitname in class SsoRequser ?
Anyone can help me ?

getServiceLocator returning Null under PHPUnittests

I'm trying to test a simple controller that authenticates a user using the LdapAdapter and using the 'ldap' array from the configuration of the Application, but phpunit is returning the following error:
Fatal error: Uncaught Error: Call to a member function get() on null in /var/www/html/app/module/Auth/src/Auth/Controller/AuthController.php:53
Stack trace:
#0 /var/www/html/app/module/Auth/test/AuthTest/Controller/AuthControllerTest.php(37): Auth\Controller\AuthController->authenticate('myuser', 'mypassword')
#1 [internal function]: AuthTest\Controller\AlbumControllerTest->testLoginAction()
#2 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestCase.php(863): ReflectionMethod->invokeArgs(Object(AuthTest\Controller\AlbumControllerTest), Array)
#3 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestCase.php(741): PHPUnit_Framework_TestCase->runTest()
#4 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestResult.php(608): PHPUnit_Framework_TestCase->runBare()
#5 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestCase.php(697): PHPUnit_Framework_TestResult->run(Object(AuthTest\Controller\AlbumControllerTest))
#6 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestSuite.php(733): PHPUnit_Framework_TestCase- in /var/www/html/app/module/Auth/src/Auth/Controller/AuthController.php on line 53
My Controller is the following:
<?php
namespace Auth\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\Adapter\Ldap as AuthAdapter;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Result;
use Auth\Form\AuthForm;
use Auth\Model\Auth;
class AuthController extends AbstractActionController
{
public function loginAction()
{
$form = new AuthForm();
$request = $this->getRequest();
if ($request->isPost()) {
$auth = new Auth();
$form->setInputFilter($auth->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()){
$auth->exchangeArray($form->getData());
$values = $form->getData();
$result = $this->authenticate($values['username'], $values['password']);
switch($result->getCode()) {
case Result::SUCCESS:
return $this->redirect()->toRoute('home');
break;
case Result::FAILURE:
break;
}
}
}
return array('form' => $form);
}
public function authenticate($username, $password){
$options = $this->getServiceLocator()->get('Config');
$authAdapter = new AuthAdapter($options['ldap'],
'username',
'password');
$authAdapter
->setIdentity($username)
->setCredential($password);
$auth = new AuthenticationService();
$result = $auth->authenticate($authAdapter);
return $result;
}
private function debug($var){
echo '<pre>';
var_dump($var);
echo '</pre>';
exit();
}
}
The TestCase:
namespace AuthTest\Controller;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
use Zend\Authentication\AuthenticationService;
use Auth\Controller\AuthController;
class AuthControllerTest extends AbstractHttpControllerTestCase
{
protected $traceError = true;
public function setUp()
{
$this->setApplicationConfig(
include '/var/www/html/app/config/application.config.php'
);
parent::setUp();
}
public function testLoginAction()
{
#Basic Access to the page
$this->dispatch('/login');
$this->assertResponseStatusCode(200);
$data = array(
'identity' => 'myuser',
'credential' => 'mypassword',
);
$auth = new AuthController();
$auth->authenticate($data['identity'], $data['credential']);
$identity = new AuthenticationService();
$this->assertEquals($data['identity'], $identity->getIdentity());
}
}
PHPUnittest's BootStrap:
<?php
namespace AuthTest;
use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;
use RuntimeException;
error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);
/**
* Test bootstrap, for setting up autoloading
*/
class Bootstrap
{
protected static $serviceManager;
public static function init()
{
$zf2ModulePaths = array(dirname(dirname(__DIR__)));
if (($path = static::findParentPath('vendor'))) {
$zf2ModulePaths[] = $path;
}
if (($path = static::findParentPath('module')) !== $zf2ModulePaths[0]) {
$zf2ModulePaths[] = $path;
}
static::initAutoloader();
// use ModuleManager to load this module and it's dependencies
$config = array(
'module_listener_options' => array(
'module_paths' => $zf2ModulePaths,
),
'modules' => array(
'Auth'
)
);
$serviceManager = new ServiceManager(new ServiceManagerConfig());
$serviceManager->setService('ApplicationConfig', $config);
$serviceManager->get('ModuleManager')->loadModules();
static::$serviceManager = $serviceManager;
}
public static function chroot()
{
$rootPath = dirname(static::findParentPath('module'));
chdir($rootPath);
}
public static function getServiceManager()
{
return static::$serviceManager;
}
protected static function initAutoloader()
{
$vendorPath = static::findParentPath('vendor');
if (file_exists($vendorPath.'/autoload.php')) {
include $vendorPath.'/autoload.php';
}
if (! class_exists('Zend\Loader\AutoloaderFactory')) {
throw new RuntimeException(
'Unable to load ZF2. Run `php composer.phar install`'
);
}
AutoloaderFactory::factory(array(
'Zend\Loader\StandardAutoloader' => array(
'autoregister_zf' => true,
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__,
),
),
));
}
protected static function findParentPath($path)
{
$dir = __DIR__;
$previousDir = '.';
while (!is_dir($dir . '/' . $path)) {
$dir = dirname($dir);
if ($previousDir === $dir) {
return false;
}
$previousDir = $dir;
}
return $dir . '/' . $path;
}
}
Bootstrap::init();
Bootstrap::chroot();
In the functional tests it works as expected, but on php unittests the error occurs in the line 53 '$options = $this->getServiceLocator()->get('Config');'.
So, how can use or set ServiceLocator to work with phpunittests?
After so much struggling on this doubt and other tests which a controller that uses an ServiceLocator, I figure that the correct way to test a controllers Action is to Mock the object or/and his methods.
I don't feel totally comfortable with this solution, but for now, this is what it is.
An other feel is that mocking an behaviour of the code is something like that breaks the DRY principle: instead of use the real code I just create a mock that half behaves like it :S
Anyway, the following code does the job for me:
$authControllerMock = $this->getMockBuilder('Auth\Controller\AuthController')
->disableOriginalConstructor()
->getMock();
$authControllerMock->expects($this->any())
->method('authenticate')
->will($this->returnValue(true);
$serviceManager = $this->getApplicationServiceLocator();
$serviceManager->setAllowOverride(true);
$serviceManager->setService('Auth\Controller\Auth', $authControllerMock);
$this->dispatch('/usermgr');
self::assertMatchedRouteName('usermgr');
self::assertControllerClass('AuthController');
self::assertControllerName('auth\controller\auth');
self::assertResponseStatusCode('200');

Retrieve data using JOIN sql in Zend Framework 2

I need to retrive data from 2 tables using join.
I have this code, but it fails with Call to undefined method Zend\Db\ResultSet\ResultSet::from():
public function getUsers($id){
$id = (int) $id;
$rowset = $this->tableGateway->select()->from(array('u' => 'user'))
->join(array('l' => 'levels'),
'u.user_id = l.id_user');
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
The SQL command would be:
select user.*,levels.name from user left join levels on user.user_id=levels.id_user
Thanks
UPDATE
Using #Mohamad changes I get:
The table name of the provided select object must match that of the table
My UsersTable.php looks like this now:
<?php
// module/Users/src/Users/Model/UsersTable.php:
namespace Users\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
class UsersTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$select = new Select();
$select->from('levels');
$select->join('user', 'levels.id=user.user_id',Select::SQL_STAR,Select::JOIN_RIGHT);
$rowset = $this->tableGateway->selectWith ( $select );
$resultSet = $rowset->current();
if (!$resultSet) {
throw new \Exception("Could not find row $id");
}
return $resultSet;
}
i think you must pass two TableGetway to UserTable construct. you have to change Module.php
look this:
public function getServiceConfig()
{
return array(
'factories' => array(
'User\Model\UserTable' => function($sm) {
$userTableGateway = $sm->get('UserTableGateway');
$levelTableGateway = $sm->get('LevelTableGateway');
$table = new UserTable($userTableGateway,$levelTableGateway);
return $table;
},
'UserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new User());
return new TableGateway('user', $dbAdapter, null, $resultSetPrototype);
},
'LevelTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Level());
return new TableGateway('level', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
then in your model:
protected $userTableGateway;
protected $levelTableGateway;
public function __construct($userTableGateway,$levelTableGateway)
{
$this->userTableGateway = $userTableGateway;
$this->levelTableGateway = $levelTableGateway;
}
public function fetchAll()
{
$select = new Select();
$select->from('levels');
$select->join('user', 'levels.id=user.user_id',Select::SQL_STAR,Select::JOIN_RIGHT);
$rowset = $this->levelTableGateway->selectWith ( $select );
$resultSet = $rowset->current();
if (!$resultSet) {
throw new \Exception("Could not find row $id");
}
return $resultSet;
}
i hope helped you

Execute In Query For ResultSet Zend Framework 2?

I want to get 3 separate row from 'cms' table.but all time i only got first row why?
My Cms.php page is:
<?php
namespace Front\Model;
use Zend\Db\TableGateway\AbstractTableGateway;
class Cms extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'cms';
$this->adapter = $adapter;
}
public function getCmsContent($id){
$id = (int) $id;
$rowset = $this->select(array('id'=>$id));
if (!$row = $rowset->current()){
throw new \Exception ('Row not found');
}
return $row;
}
}
My Controller is :FrontController.php is:
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Front\Model\Cms;
use Front\Model\Setting;
use Front\Model\Slider;
class FrontController extends AbstractActionController
{
public function indexAction()
{
$this->layout()->slider_data = $this->getSlider()->fetchAll();
$this->layout()->setting_data = $this->getSetting()->getSettingContent(1);
return array('cms_data'=>$this->getCms()->getCmsContent('1,2,3'));
}
public function getSlider(){
return $this->getServiceLocator()->get('Front/Model/Slider');
}
public function getCms(){
return $this->getServiceLocator()->get('Front\Model\Cms');
}
public function getSetting(){
return $this->getServiceLocator()->get('Front/Model/Setting');
}
}
My Model is:
namespace Front;
class Module
{
public function getAutoloaderConfig()
{
return array('Zend\Loader\StandardAutoloader' =>
array('namespaces' =>
array(__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Front\Model\AlbumTable' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\AlbumTable($dbAdapter);
return $table;
},
'Front\Model\Cms' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\Cms($dbAdapter);
return $table;
},
'Front\Model\Setting' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\Setting($dbAdapter);
return $table;
},
'Front\Model\Slider' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Front\Model\Slider($dbAdapter);
return $table;
},
),
);
}
}
?>
My View:index.php Page is:
<?php print_R($cms_data); ?>
try this code block and change the $condition according to you
public function getCmsContent($id){
$id = (int) $id;
$select = new Select();
$select->from(array('t' => $this->table))
->where(array($condition));
$statement = $this->adapter->createStatement();
$select->prepareStatement($this->adapter, $statement);
$result = $statement->execute();
$rows = array();
if ($result->count()) {
$rows = new ResultSet();
return $rows->initialize($result)->toArray();
}
}
You try:
class Cms extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'cms';
$this->adapter = $adapter;
}
public function getCmsContent($id){
return $this->select(array(
new Expression('id IN (?)', array($id)),
));
}
}
Get contents
$contents = $this->getCms()->getCmsContent(array(1, 2, 3));
$results = array();
foreach($contents as $content){
$results[] = $content;
}
print_r($results);

Zend_Log_Writer_Db - Call to undefined method Zend_Config::insert()

I am running php 5.2.12 and Zend Framework 5.0.2
In my Bootstrap.php, I initialize our database connection, and initialize our logger... placing both in the registry.
However, when I try to log info in the IndexController.php, it gives the following message:
"*Fatal error: Call to undefined method Zend_Config::insert() in /usr/local/zendsvr/share/ZendFramework/library/Zend/Log/Writer/Db.php on line 137*"
At the bottom of this post, you will find the Zend Framework's class file, db.php , and the _write function being called.
I believe the problem is that I am getting the database connection options from my application.ini... and there is no insert() function defined in my application.ini for the database. But I dont really know how to add one to the config, or how I should be doing this.
Bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initConfig()
{
Zend_Registry::set('config', new Zend_Config($this->getOptions()));
}
protected function _initDatabases()
{
$this->bootstrap('multidb');
$resource = $this->getPluginResource('multidb');
$databases = Zend_Registry::get('config')->resources->multidb;
foreach ($databases as $name => $adapter)
{
$db_adapter = $resource->getDb($name);
Zend_Registry::set($name, $db_adapter);
}
}
protected function _initLog()
{
$db = Zend_Registry::get('config')->resources->multidb->as400;
$columnMapping = array('ILGID' => 'id', //1 numeric
'ILGLVL' => 'priority', //2 numeric
'ILGDTE' => 'date', //yymmdd
'ILGTME' => 'time', //hhmmss
'ILGPGM' => 'program', //40 alnum
'ILGURL' => 'url', //2100
'ILGUSR' => 'user', //30
'ILGMSG' => 'message'); //1000
$writer = new Zend_Log_Writer_Db($db, 'dwhlib.intralog', $columnMapping);
$logger = new Zend_Log($writer);
$date = new Zend_Date();
date_default_timezone_set('America/Chicago');
$logger->setEventItem('id' , 1);
$logger->setEventItem('date' , $date->get('Ymd'));
$logger->setEventItem('time' , $date->get('Hms'));
$logger->setEventItem('program' , 'testProgramName'); $logger->setEventItem('url' , $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
$logger->setEventItem('user' , gethostbyaddr($_SERVER['REMOTE_ADDR']));
Zend_Registry::set('logger', $logger);
}
}
application.ini
resources.multidb.as400.adapter = "db2"
resources.multidb.as400.host = "i5"
resources.multidb.as400.username = "removedUsername"
resources.multidb.as400.password = "removedPassword"
resources.multidb.as400.dbname = "*LOCAL"
resources.multidb.as400.default = true
IndexController.php
include("/www/zendserver/htdocs/development/application/models/as400.php");
class IndexController extends Zend_Controller_Action
{
public function init()
{
Zend_Registry::get('logger')->info("this is a test message");
}
public function indexAction()
{
// action body
}
}
as400.php
Class default_Model_As400 extends Zend_Db {
public static function ExecuteSelect($sql, $mode = Zend_Db::FETCH_ASSOC, $log = false)
{
$stmt = self::getStmt($sql);
$stmt->setFetchMode($mode);
$stmt->execute();
if($log === true) {
Zend_Registry::get('logger')->info($sql);
}
$rows = $stmt->fetchAll();
return $rows;
}
private static function getStmt($sql){
$db = Zend_Registry::get('config')->resources->multidb->as400;
$abstractAdapter = new Zend_Db_Adapter_Db2($db);
return new Zend_Db_Statement_DB2($abstractAdapter, $sql);
}
public function insert($libAndFile, $arrData){
echo "this was hit!!";
}
}
db.php
class Zend_Log_Writer_Db extends Zend_Log_Writer_Abstract
{
public function __construct($db, $table, $columnMap = null)
{
$this->_db = $db;
$this->_table = $table;
$this->_columnMap = $columnMap;
}
protected function _write($event)
{
if ($this->_db === null) {
require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Database adapter is null');
}
if ($this->_columnMap === null) {
$dataToInsert = $event;
} else {
$dataToInsert = array();
foreach ($this->_columnMap as $columnName => $fieldKey) {
$dataToInsert[$columnName] = $event[$fieldKey];
}
}
$this->_db->insert($this->_table, $dataToInsert);
}
}
What is happening: you are calling a method called insert() on a Zend_Config instance.
What you want: call a method insert() through a Zend_Db_Adapter.
There is something wrong in your _initLog() bootstrap method:
$db = Zend_Registry::get('config')->resources->multidb->as400;
$writer = new Zend_Log_Writer_Db($db, 'dwhlib.intralog', $columnMapping);
Zend_Log_Writer_Db expects a Zend_Db adapter as a first constructor parameter. To fix this, since you already registered your database adapter in the registry, you should do something like this :
$dbName = Zend_Registry::get('config')->resources->multidb->as400;
$db = Zend_Registry::get($dbName);
$writer = new Zend_Log_Writer_Db($db, 'dwhlib.intralog', $columnMapping);

Categories