Laravel inserting data - database

I have FotoController.php
and this is part of function:
$img = array(
'name' => $filename,
'gid' => $id,
);
$s = new Img($img);
$create = $s->save();
My img model:
class Img extends Eloquent {
public $timestamps = false;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'images';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
//protected $hidden = array('remember_token');
protected $fillable = array('name', 'gid', 'views', 'likes');
}
But it doesn't add new record into the database.

You can't create a new object and fill it at the same time this way, you need to use the fill method:
$img = array(
'name' => $filename,
'gid' => $id,
);
$s = new Img();
$s->fill($img);
$s->save();
Or you can use the static create method on your model:
$img = array(
'name' => $filename,
'gid' => $id,
);
$s = Img::create($img);

Related

Is there any where to determine name of table order_product table

I'm trying to create and edit order with laravel , but when i call create function i have an error (Base table or view not found: 1146 Table 'easyres.order_products) and then if i change table name to order_products i have same error but with (order_product)
Orderproduct model:
protected $fillable = [
'count' , 'price'
];
Order model :
public function products(){
return $this->belongsToMany('App\Product')->withPivot('count')->withPivot('price');
}
Product model:
public function order(){
return $this->belongsToMany('App\Order');
}
function of create:
public function createOrder(Request $request)
{
$order = new Order;
$order->status = $request->status;
$order->user_id = auth()->user()->id;
$order->save();
$product_ids = $request->products;
foreach ($product_ids as $index => $productId) {
$id = $productId['product_id'];
$count = $productId['count'];
$product = Product ::find($id);
$orderProduct = new Orderproduct;
$orderProduct->product_id = $id;
$orderProduct->order_id = $order->id;
$orderProduct->count = $count;
$orderProduct->price = $product->product_price;
$orderProduct->save();
}
return response()->json([
'message' => 'Success'
],200);
}
function of edit :
public function EditOrder(Request $request , $id){
$order = Order::find($id);
$order->status = $request->status;
$order->user_id = $request->user_id;
$order->update();
$product_ids = $request->products;
$selectedItems = [];
foreach ( $product_ids as $key => $productId) {
$id1 = $productId['product_id'];
$product = Product ::find($id);
$count = $productId['count'];
$selectedItems[$id1] = ['product_id' => $productId['product_id'] , 'count' => $productId['count'] , 'price' => $product->product_price];
$order->products()->updateExistingPivot($id1, $selectedItems[$id1]);
}
return response()->json([
'message' => 'Success'
],200);
}
I want to determine order_product table's name
In your OrderProduct model set the table name as a property
protected $table = "order_product";
Because Eloquent assumes a plural form as a table name

How to Build Multi-step Forms with Preview data fill page in drupal 8?

many days I working on drupal 8 custom form module which is the multi-step form I have complete this using SessionManagerInterface that's work fine but I want to display all data in one page before submit how can I achieve this .here I include snapshot here
demo.routing.yml
demo.multistep_one:
path: '/demo/multistep-one'
defaults:
_form: '\Drupal\demo\Form\Multistep\MultistepOneForm'
_title: 'First form'
requirements:
_permission: 'access content'
demo.multistep_two:
path: '/demo/multistep-two'
defaults:
_form: '\Drupal\demo\Form\Multistep\MultistepTwoForm'
_title: 'Second form'
requirements:
_permission: 'access content'ent'
MultistepFormBase.php
namespace Drupal\demo\Form\Multistep;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\SessionManagerInterface;
use Drupal\user\PrivateTempStoreFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class MultistepFormBase extends FormBase {
/**
* #var \Drupal\user\PrivateTempStoreFactory
*/
protected $tempStoreFactory;
/**
* #var \Drupal\Core\Session\SessionManagerInterface
*/
private $sessionManager;
/**
* #var \Drupal\Core\Session\AccountInterface
*/
private $currentUser;
/**
* #var \Drupal\user\PrivateTempStore
*/
protected $store;
/**
* Constructs a \Drupal\demo\Form\Multistep\MultistepFormBase.
*
* #param \Drupal\user\PrivateTempStoreFactory $temp_store_factory
* #param \Drupal\Core\Session\SessionManagerInterface $session_manager
* #param \Drupal\Core\Session\AccountInterface $current_user
*/
public function __construct(PrivateTempStoreFactory $temp_store_factory, SessionManagerInterface $session_manager, AccountInterface $current_user) {
$this->tempStoreFactory = $temp_store_factory;
$this->sessionManager = $session_manager;
$this->currentUser = $current_user;
$this->store = $this->tempStoreFactory->get('multistep_data');
}
/**
* {#inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('user.private_tempstore'),
$container->get('session_manager'),
$container->get('current_user')
);
}
/**
* {#inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Start a manual session for anonymous users.
if ($this->currentUser->isAnonymous() && !isset($_SESSION['multistep_form_holds_session'])) {
$_SESSION['multistep_form_holds_session'] = true;
$this->sessionManager->start();
}
$form = array();
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Submit'),
'#button_type' => 'primary',
'#attributes' => array(
'class' => array(
'btn btn-register'
),
),
);
return $form;
}
MultistepOneForm.php which child form
namespace Drupal\demo\Form\Multistep;
use Drupal\Core\Form\FormStateInterface;
class MultistepOneForm extends MultistepFormBase {
/**
* {#inheritdoc}.
*/
public function getFormId() {
return 'multistep_form_one';
}
/**
* {#inheritdoc}.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
$form['fname'] = array(
'#type' => 'textfield',
'#title' => $this->t('Your name'),
'#default_value' => $this->store->get('fname') ? $this->store->get('fname') : '',
'#attributes' => array(
'class' => array(
'form-control'
),
),
);
$form['lname'] = array(
'#type' => 'textfield',
'#title' => $this->t('Your Last Name'),
'#default_value' => $this->store->get('lname') ? $this->store->get('lname') : '',
'#attributes' => array(
'class' => array(
'form-control'
),
),
$form['actions']['submit']['#value'] = $this->t('Continue');
return $form;
}
/**
* {#inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->store->set('fname', $form_state->getValue('fname'));
$this->store->set('lname', $form_state->getValue('lname'));
$form_state->setRedirect('demo.multistep_two');
}
}
MultistepTwoForm.php
namespace Drupal\demo\Form\Multistep;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
class MultistepTwoForm extends MultistepFormBase {
/**
* {#inheritdoc}.
*/
public function getFormId() {
return 'multistep_form_two';
}
/**
* {#inheritdoc}.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
$form['jfname'] = array(
'#type' => 'textfield',
'#title' => $this->t('Joint Account Holder First Name'),
'#attributes' => array(
'class' => array(
'form-control'
),
),
);
$form['jlname'] = array(
'#type' => 'textfield',
'#title' => $this->t('Joint Account Holder Last Name'),
'#attributes' => array(
'class' => array(
'form-control'
),
),
);
$form['actions']['previous'] = array(
'#type' => 'link',
'#title' => $this->t('Previous'),
'#url' => Url::fromRoute('demo.multistep_one'),
'#suffix' => '</div>',
'#attributes' => array(
'class' => array(
'btn btn-register'
),
),
);
$form['actions']['submit']['#value'] = $this->t('Continue');
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->store->set('jfname', $form_state->getValue('jfname'));
$this->store->set('jlname', $form_state->getValue('jlname'));
// $form_state->setRedirect('demo.multistep_three');
}
}
here my concern is raised How to display all data according to my snapshot.what action needs to be taken display data. one thing is that i have 3 month experience about drupal so can't take decision what i will do? this code is example of www.sitepoint.com and I take form three and session data is display in label whether it good or not i don't know give me direction appropriate
thanks in advance
In your setup, you are submitting the multiform in MultistepTwoForm.
Change this as follows:
Build one more form: MultiStepPreview. This will hold your preview.
Do Not submit the form in MultistepTwoForm but redirect the form to MultiStepPreview using $form_state->setRedirect()
In MultiStepPreview:
read the keys in the store
build a form element containing the preview (I made a html table to contain the preview)
submit the form.
class OverviewForm extends MultiStepFormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
// get data from the store
$your_details = $this->store->get('your_details');
$order = $this->store->get('order_details');
// make a HTML table containing the data in store
$markup = '<table>';
// loop through $your_details and $your_order and put them in $markup
$form = parent::buildForm($form, $form_state);
$form['preview'] = [
'#markup' => $markup,
];
//in my setup all the buttons are build by MultiStepFormBase
return $form;
}
}

How to populate select element in zend 1.12 from db

i'm creating a application in which i need to populate data in select element from a db table.
i need to populate user roles from db
my form code is
$this->pass2->addValidator('Identical', false, array('token' => 'pass1'));
$this->addElement('select', 'userrole', array(
'class' => 'form-control',
'required' => true,
'multiOptions' =>
));
what should i do with multi options ?,
is there any way to load data from db in element using controller ,please helpme
thanks
What I have done in the past is to pass the db-adapter (or a model that knows how to do the required db query) to the form as a constructor parameter.
Something like this:
class Application_Form_MyForm extends Zend_Form
{
protected $db;
public function __construct($db)
{
$this->db = $db;
// Don't forget to call the parent __construct. Ultimately
// it is the parent __construct() that calls your init()
// method that adds your elements
parent::__construct();
}
public function init()
{
// Create your form elements
// $this->addElement('text', 'my_text_field'); // etc
// Now your select field...
$this->addElement('select', 'my_select', array(
'multiOptions' => $this->buildMultiOptions(),
'validators' => array(
// blah, blah
),
);
}
protected function buildMultiOptions()
{
$select = $this->db->select()
->from('my_table', array(
'my_value_column',
'my_display_column'
))
->order(array(
'my_display_column ASC',
));
$results = $this->db->query($select)->fetchAll();
$return = array();
foreach ($results as $row) {
$return[$row['my_value_column']] = $row['my_display_column'];
}
return $return;
}
}
Then in the controller action, when you instantiate your form, you grab the db-adapter and pass it in as a constructor parameter:
$db = $this->getInvokeArg('bootstrap')->getResource('db');
$form = new Application_Form_MyForm($db);
// Then process your form as usual
on case with is necessary populate options outside form class.
$form->getElement( 'ele_name' )
->setConfig(new Zend_Config( array(
'multiOptions' => array('option1','option2') )
)));

Magento 2 adminhtml multiselect and showing selected options after save

How do I get the Magento2 Adminhtml Form with a Multiselect to select the saved options?
Here is my Adminhtml Form Class for reference.
namespace RussellAlbin\Blog\Block\Adminhtml\Post\Edit;
/**
* Adminhtml blog post edit form
*/
class Form extends \Magento\Backend\Block\Widget\Form\Generic
{
/**
* #var \RussellAlbin\Blog\Model\Category\Source\ListCategories
*/
protected $_categories;
/**
* #var \RussellAlbin\Blog\Model\Postcategory
*/
protected $_postcategory;
/**
* #var \Magento\Store\Model\System\Store
*/
protected $_systemStore;
/**
* #param \Magento\Backend\Block\Template\Context $context
* #param \Magento\Framework\Registry $registry
* #param \Magento\Framework\Data\FormFactory $formFactory
* #param \Magento\Store\Model\System\Store $systemStore
* #param \RussellAlbin\Blog\Model\Category\Source\ListCategories $categories
* #param \RussellAlbin\Blog\Model\Postcategory $postcategory
* #param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore,
\RussellAlbin\Blog\Model\Category\Source\ListCategories $categories,
\RussellAlbin\Blog\Model\Postcategory $postcategory,
array $data = []
) {
$this->_categories = $categories;
$this->_systemStore = $systemStore;
$this->_postcategory = $postcategory;
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* Init form
*
* #return void
*/
protected function _construct()
{
parent::_construct();
$this->setId('blog_post_form');
$this->setTitle(__('Blog Post Information'));
}
/**
* Prepare form
*
* #return $this
*/
protected function _prepareForm()
{
/** #var \RussellAlbin\Blog\Model\Post $model */
$model = $this->_coreRegistry->registry('blog_post');
/** #var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create(
['data' => ['id' => 'edit_form', 'action' => $this->getData('action'), 'method' => 'post']]
);
$form->setHtmlIdPrefix('post_');
$fieldset = $form->addFieldset(
'base_fieldset',
['legend' => __('General Information'), 'class' => 'fieldset-wide']
);
if ($model->getPostId()) {
$fieldset->addField('post_id', 'hidden', ['name' => 'post_id']);
}
// Gather our existing categories
$currentCategories = $this->_getExistingCategories( $model );
// Get all the categories that in the database
$allCategories = $this->_categories->toOptionArray();
$field = $fieldset->addField(
'blog_categories',
'multiselect',
[
'label' => __('Categories'),
'required' => true,
'name' => 'blog_categories',
'values' => $allCategories,
'value' => $currentCategories
]
);
$form->setValues($model->getData());
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
/**
* #param $model
* #return array
*/
private function _getExistingCategories( $model )
{
// Get our collection
$existingCategories = $this->_postcategory->getCollection()
->addFieldToSelect('category_id')
->addFieldToFilter('post_id', $model->getId());
// Setup our placeholder for the array of categories needed to set back on the value of the multiselect
$itemList = array();
foreach($existingCategories as $_item)
{
$itemList[] = $_item['category_id'];
}
return $itemList;
}
}
I looked back at some work I have done in Magento 1.x and I the only way I got this to work before was using javascript and the setAfterElementHtml to set the options that matched. I remember hating this method of getting it accomplished because it seemed like a work around.
I found the issue.
I did not have the values saved on the model.
// This is what shows it as selected on reload
$model->setData('blog_categories', $categories);
$fieldset->addField(
'blog_categories',
'multiselect',
[
'name' => 'blog_categories[]',
'label' => __('Categories'),
'title' => __('Categories'),
'required' => true,
'values' => $optionArray,
'disabled' => false
]
);

ZF2 Dafault Database Session Storage

I am busy writing a DB Session module so I can quickly install it between multiple applications. The module will be loaded from the autoloader as the first module to be started. What I'm trying to accomplish is to change the default session container / session handler to be the default session handler for all modules and it should also be database hosted sessions. I've been strugling with zf2 session handler for quite a while now and the errors in the logs make 0 sense. So here what I have so far. A basic module with Module.php containing...
namespace DBSession;
use Zend\Mvc\ModuleRouteListener;
class Module {
public function onBootstrap($e) {
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$config = $e->getApplication()->getServiceManager()->get('Config');
$controller = $e->getTarget();
$controller->config = $config;
new \DBSession\Storage\DBStorage();
}
public function getConfig() {
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig() {
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
And the actual class that initiates the DB session handler.
namespace DBSession\Storage;
use Zend\Session\SaveHandler\DbTableGateway;
use Zend\Session\SaveHandler\DbTableGatewayOptions;
use Zend\Db\Adapter\Adapter;
use Zend\Session\SessionManager;
use Zend\Session\Container;
class DBStorage {
public function __construct() {
$dbAdapter = new Adapter(array(
'driver' => 'Mysqli',
'host' => 'localhost',
'dbname' => 'zf2_session',
'username' => 'zf2',
'password' => 'testme',
'options' => array(
'buffer_results' => true,
),
));
$tableGateway = new \Zend\Db\TableGateway\TableGateway('session', $dbAdapter);
$gwOpts = new DbTableGatewayOptions();
$gwOpts->setDataColumn('data');
$gwOpts->setIdColumn('id');
$gwOpts->setLifetimeColumn('lifetime');
$gwOpts->setModifiedColumn('modified');
$gwOpts->setNameColumn('name');
$saveHandler = new DbTableGateway($tableGateway, $gwOpts);
$sessionManager = new SessionManager();
$sessionManager->setSaveHandler($saveHandler);
return Container::setDefaultManager($sessionManager);
}
}
When trying to create a session I see the following in the logs which I have 0 clue how to fix. This is starting to make me hate magic...
[29-Nov-2012 20:47:28 UTC] PHP Fatal error: Uncaught exception 'Zend\Db\Sql\Exception\InvalidArgumentException' with message 'Not a valid magic property for this object' in /document_root/vendor/zendframework/zendframework/library/Zend/Db/Sql/Select.php:764
Stack trace:
#0 /document_root/vendor/zendframework/zendframework/library/Zend/Db/Sql/Select.php(163): Zend\Db\Sql\Select->__get('tableReadOnly')
#1 /document_root/vendor/zendframework/zendframework/library/Zend/Db/Sql/Select.php(146): Zend\Db\Sql\Select->from('session')
#2 /document_root/vendor/zendframework/zendframework/library/Zend/Db/Sql/Sql.php(65): Zend\Db\Sql\Select->__construct('session')
#3 /document_root/vendor/zendframework/zendframework/library/Zend/Db/TableGateway/AbstractTableGateway.php(191): Zend\Db\Sql\Sql->select()
#4 /document_root/vendor/zendframework/zendframework/library/Zend/Session/SaveHandler/DbTableGateway.php(134): Zend\Db\TableGateway\AbstractTableGateway->select(Array)
#5 [internal function]: Zend\Session\SaveHandler\DbTableGateway->write(' in /document_root/vendor/zendframework/zendframework/library/Zend/Db/Sql/Select.php on line 764
update :
zend framework >= 2.2, this issue is no more .
Old answer :
I have faced same issue on storing session into database , I have written initDbSession function inside basic module class \module\Application\Module.php
class Module
{
public function onBootstrap(MvcEvent $e)
{
$e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
// session start from here
$this->initDbSession( $e );
}
/**
* Store session into database
*
* #param type $e
*/
private function initDbSession( MvcEvent $e )
{
// grab the config array
$serviceManager = $e->getApplication()->getServiceManager();
$config = $serviceManager->get('config');
$dbAdapter = $serviceManager->get('Zend\Db\Adapter\Adapter');
/* some how this not works for me
$sessionOptions = new \Zend\Session\SaveHandler\DbTableGatewayOptions( null );
$sessionTableGateway = new \Zend\Db\TableGateway\TableGateway('session', $dbAdapter);
$saveHandler = new \Zend\Session\SaveHandler\DbTableGateway($sessionTableGateway, $sessionOptions);
*/
/* I written my own save handler , I am using mysql as database */
$saveHandler = new \My\Session\SaveHandler\Mysql( $config['db'] );
$sessionConfig = new \Zend\Session\Config\SessionConfig();
$sessionConfig->setOptions($config['session']);
// pass the saveHandler to the sessionManager and start the session
$sessionManager = new \Zend\Session\SessionManager( $sessionConfig , NULL, $saveHandler );
$sessionManager->start();
\Zend\Session\Container::setDefaultManager($sessionManager);
}
// other function goes here ...
Here my config file , which is located in \config\autoload\global.php
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=zf2;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
'buffer_results' => true
),
'username' => 'root',
'password' => '',
'host' => 'localhost',
'dbname' => 'zf2',
),
'session' => array(
'remember_me_seconds' => 2419200,
'use_cookies' => true,
'cookie_httponly' => true,
'cookie_lifetime' => 2419200,
'gc_maxlifetime' => 2419200,
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory'
)
)
);
Mysql Table structure is
CREATE TABLE `session` (
`id` CHAR(32) NOT NULL DEFAULT '',
`name` VARCHAR(255) NOT NULL,
`modified` INT(11) NULL DEFAULT NULL,
`lifetime` INT(11) NULL DEFAULT NULL,
`data` TEXT NULL,
PRIMARY KEY (`id`)
)COLLATE='utf8_general_ci' ENGINE=InnoDB;
Custom Mysql save handler class is given below . I have written this class, because new Zend\Session\SaveHandler\DbTableGateway
not working on my server . My custom Mysql session save handler class written on \library\My\Session\SaveHandler\Mysql.php
<?php
namespace My\Session\SaveHandler;
use Zend\Session\SaveHandler\SaveHandlerInterface;
/**
* Description of Mysql
*
* #author rab
*/
class Mysql implements SaveHandlerInterface
{
/**
* Session Save Path
*
* #var string
*/
protected $sessionSavePath;
/**
* Session Name
*
* #var string
*/
protected $sessionName;
/**
* Lifetime
* #var int
*/
protected $lifetime;
/**
* Constructor
*
*/
public function __construct( $dbConfig )
{
$this->dbconn = mysql_connect(
$dbConfig['host'],
$dbConfig['username'],
$dbConfig['password']
);
if ( $this->dbconn ) {
return mysql_select_db($dbConfig['dbname'], $this->dbconn);
}
}
/**
* Open the session
*
* #return bool
*/
public function open( $savePath, $name )
{
$this->sessionSavePath = $savePath;
$this->sessionName = $name;
$this->lifetime = ini_get('session.gc_maxlifetime');
return true;
}
/**
* Close the session
*
* #return bool
*/
public function close()
{
return mysql_close($this->dbconn);
}
/**
* Read the session
*
* #param int session id
* #return string string of the sessoin
*/
public function read($id)
{
$id = mysql_real_escape_string($id);
$sql = "SELECT `data` FROM `session` " .
"WHERE id = '$id'";
if ( $result = mysql_query($sql, $this->dbconn)) {
if ( mysql_num_rows($result) ) {
$record = mysql_fetch_assoc($result);
return $record['data'];
}
}
return '';
}
/**
* Write the session
*
* #param int session id
* #param string data of the session
*/
public function write($id, $data )
{
$data = (string) $data ;
$dbdata = array(
'modified' => time(),
'data' => mysql_real_escape_string( $data ) ,
);
$selectSql = "SELECT * FROM session
WHERE id = '$id' AND name = '{$this->sessionName}' ";
$rs = mysql_query( $selectSql, $this->dbconn );
if ( $rs = mysql_query( $selectSql , $this->dbconn)) {
if ( mysql_num_rows($rs) ) {
$updateSql = "UPDATE `session` SET
`modified`= '".$dbdata['modified'] . "' ,
`data`= '".$dbdata['data']. "'
WHERE id= '$id' AND name = '{$this->sessionName}' ";
mysql_query( $updateSql , $this->dbconn );
return true;
}
}
$dbdata['lifetime'] = $this->lifetime;
$dbdata['id'] = $id;
$dbdata['name'] = $this->sessionName;
$insertSql = "INSERT INTO session (". implode(',' , array_keys($dbdata)) .")"
."VALUES ('" . implode("','" , array_values( $dbdata )). "')";
return mysql_query( $insertSql, $this->dbconn);
}
/**
* Destoroy the session
*
* #param int session id
* #return bool
*/
public function destroy($id)
{
$sql = sprintf("DELETE FROM `session` WHERE `id` = '%s'", $id);
return mysql_query($sql, $this->dbconn);
}
/**
* Garbage Collector
*
* #param int life time (sec.)
* #return bool
*/
public function gc( $maxlifetime )
{
$sql = sprintf("DELETE FROM `session` WHERE `modified` < '%s'",
mysql_real_escape_string(time() - $maxlifetime)
);
return mysql_query($sql, $this->dbconn);
}
}
Which saves my session values into db table . For more information you can check http://php.net/manual/en/function.session-set-save-handler.php
After all of the fixes that have recently gone into ZF2 my original solution is now working without modification however, I have added a new composer module for anyone that wants to use it, it reduces the need to do it all manually.
Installation details are in the readme file on: https://github.com/Nitecon/DBSessionStorage
Enjoy and let me know if you have any issues.
Here's another similar solution:
How to use cookie in Zend Framework 2?
make sure you change this line:
Session::setDefaultManager($sessionManager);
With this one:
Container::setDefaultManager($sessionManager);
Using:
use Zend\Session\Container;

Resources