Calling db in a function - eloquent

I'm trying to use a function that I wrote inside my routes.php file:
the function is this:
function userScore($uid) {
$db = $app->get('db');
//calcolo punteggio totale
$query_punti = $db->table('prodotti_sounding')
->where('id_utente', $uid)
->select('punti')
->get();
$totale_punti = 0;
foreach($query_punti as $item) {
$totale_punti += $item->punti;
}
}
it returns this error:
Slim Application Error The application could not run because of the
following error:
Type: Error Message: Call to a member function get() on null
where am I wrong?
EDIT
my relevant code in routes.php after the first answer is:
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Illuminate\Database\Connection;
use Slim\Http\UploadedFile;
use Illuminate\Support\Facades\DB as DB;
$container = $app->getContainer();
$app->post('/sendbarcode', function ($request, $response){
/* parametri barcode */
/** #var Container $this */
/** #var Connection $db */
$barcode = $request->getParsedBodyParam('barcode');
$id_utente = $request->getParsedBodyParam('id_utente');
$db = $this->get('db');
// prepare data for json
$array['itacheck'] = 0;
if(checkbarcode($barcode) == 1 ) {
$array['it_check'] = 1;
$array['punti'] = 25;
$array['totalepunti'] = userScore($id_utente);
}
$array['barcode'] = $rows;
if(count($rows) > 0){
return $response->withJson($array, 200, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_LINE_TERMINATORS);
}
});
function userScore($uid) {
//calcolo punteggio totale in base alle segnalazioni pregresse
$query_punti = DB::table('prodotti_sounding')
->where('id_utente', $uid)
->select('punti')
->get();
// check total points
$totale_punti = 0;
foreach($query_punti as $item) {
$totale_punti += $item->punti;
}
}

Error becomes $db = $app->get('db');, because you not defained $app variable. Instaed of you can use this
//calcolo punteggio totale
$query_punti = DB::table('prodotti_sounding')
->where('id_utente', $uid)
->select('punti')
->get();
DB full class name is \Illuminate\Support\Facades\DB
Edit
That case add $app attribute in function argument
function userScore($uid, $app) {
$db = $app->get('db');

Related

Changed mysql to mysqli and can't connect to database

I am not very experienced in this field so this is why I am seeking help.
I recently changed hosts and a script stopped working. After moving all files the new hosts said mysql is deprecated, so after doing a bit of search I decided to change mysql with mysqli and that deprecated error was gone. But now I get a new error (error select db). I think I must make adidtional changes to the script to connect mysqli. This is the file I have
<?php
class Model{
var $conn;
public function openDb($dbhost, $dbuser, $dbpass, $dbname, $conn)
{
//echo "Se creo la conexion ";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysqli');
mysqli_select_db($dbname) or die('Error select db');
mysqli_query("SET NAMES utf8");
return $conn;
}
public function closeDb($conn)
{
mysqli_close($conn);
}
public function query($query)
{
if ($result = mysqli_query($query) or die("Error de Query: </br >" . mysqli_error()."<br/>".$query)) {
//if ($result = mysqli_query($query)) {
} else {
$result = false;
}
return $result;
}
function __construct()
{
$this->openDb(dbhost, dbuser, dbpass, dbname, $conn);
}
//insertGenerico con indedices asiciativos
function insertar($tabla, $datos)
{
$columnas = implode(", ", array_keys($datos));
$valores = implode(", ", $datos);
$query = "INSERT INTO $tabla
($columnas)
VALUES
(" . $valores . ")";
return $this -> query($query);
}
function insertarRelacionArray($tabla, $tablaRelacion, $datos)
{
foreach ($datos as $row) {
$query = "INSERT INTO $tabla
($tablaRelacion[0],$tablaRelacion[2])
VALUES
($tablaRelacion[1],$row)";
//echo '<br>'.$query;
$this -> query($query);
}
}
//getGenerico
function get($tabla, $where = false, $order = false)
{
$query = "SELECT *
FROM $tabla
$where
$order";
return $this -> query($query);
}
//deleteGenerico
function delete($tabla, $id, $idTag = false)
{
if($idTag==false)
$idTag = "id";
$query = "DELETE FROM $tabla
WHERE $idTag = $id";
return $this -> query($query);
}
//update generico
function update($tabla, $datos, $id, $idTag = false)
{
$columnas = array_keys($datos);
$SET = 'SET ';
$i = 0;
foreach ($datos as $key => $value) {
if (next($datos)) {
$SET .= "$key = $value ,";
} else {
$SET .= "$key = $value ";
}
}
if($idTag==false)
$idTag = "id";
$query = "UPDATE $tabla $SET WHERE $idTag = $id;";
return $this -> query($query);
}
}
?>
As described on http://php.net/manual/en/mysqli.select-db.php first parameter should be $link.
bool mysqli_select_db ( mysqli $link , string $dbname )
So change
mysqli_select_db($dbname) or die('Error select db');
to
mysqli_select_db($conn, $dbname) or die('Error select db');
and it should work.
I think that you need to return $conn in your _construct function too, or store it in the object ($this->conn = $conn) so you can use it again.
In addition (thanks to Ki Jéy) you should also update
mysql_query($query)
to
mysqli_query($conn, $query)
and
mysql_real_escape_string($string)
to
mysqli_real_escape_string ($conn, $string)

Magento 2 category selector in system configuration

How to get category selector in system configuration in magento 2?
I need to get all levels of categories in the admin configuration section as multi select option. I have added the following code and I am getting desired result. But I want to do it using recursive function . Please help me to do the same.
namespace Vendor\Productslider\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
use Magento\Catalog\Helper\Category;
class Categorylist implements ArrayInterface
{
protected $_categoryHelper;
protected $categoryRepository;
public function __construct(
\Magento\Catalog\Helper\Category $catalogCategory,
\Magento\Catalog\Model\CategoryRepository $categoryRepository
)
{
$this->_categoryHelper = $catalogCategory;
$this->categoryRepository = $categoryRepository;
}
/*
* Return categories helper
*/
public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
{
return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
}
/*
* Option getter
* #return array
*/
public function toOptionArray()
{
$arr = $this->toArray();
$ret = [];
foreach ($arr as $key => $value)
{
$ret[] = [
'value' => $key,
'label' => $value
];
}
return $ret;
}
/*
* Get options in "key-value" format
* #return array
*/
public function toArray()
{
$categories = $this->getStoreCategories(true,false,true);
$categoryList = $this->renderCategories($categories);
return $categoryList;
}
public function renderCategories($_categories)
{
$categoryList = array();
foreach ($_categories as $category){
$categoryList[$category->getEntityId()] = __($category->getName()); // Main categories
$categoryObj = $this->categoryRepository->get($category->getId());
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $subcategory) {
$categoryList[$subcategory->getEntityId()] = __('--'.$subcategory->getName()); // 1st level Sub categories
if($subcategory->hasChildren()) {
$childCategoryObj = $this->categoryRepository->get($subcategory->getId());
$childSubcategories = $childCategoryObj->getChildrenCategories();
foreach($childSubcategories as $childSubcategory) {
$categoryList[$childSubcategory->getEntityId()] = __('----'.$childSubcategory->getName()); // 2nd level Sub categories
}
}
}
}
return $categoryList;
}
}
Thank God !!
I have find a solution
namespace Vendor\Productslider\Model\Config\Source;
use Magento\Framework\Option\ArrayInterface;
use Magento\Catalog\Helper\Category;
class Categorylist implements ArrayInterface
{
protected $_categoryHelper;
protected $categoryRepository;
protected $categoryList;
public function __construct(
\Magento\Catalog\Helper\Category $catalogCategory,
\Magento\Catalog\Model\CategoryRepository $categoryRepository
)
{
$this->_categoryHelper = $catalogCategory;
$this->categoryRepository = $categoryRepository;
}
/*
* Return categories helper
*/
public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
{
return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
}
/*
* Option getter
* #return array
*/
public function toOptionArray()
{
$arr = $this->toArray();
$ret = [];
foreach ($arr as $key => $value)
{
$ret[] = [
'value' => $key,
'label' => $value
];
}
return $ret;
}
/*
* Get options in "key-value" format
* #return array
*/
public function toArray()
{
$categories = $this->getStoreCategories(true,false,true);
$categoryList = $this->renderCategories($categories);
return $categoryList;
}
public function renderCategories($_categories)
{
foreach ($_categories as $category){
$i = 0;
$this->categoryList[$category->getEntityId()] = __($category->getName()); // Main categories
$list = $this->renderSubCat($category,$i);
}
return $this->categoryList;
}
public function renderSubCat($cat,$j){
$categoryObj = $this->categoryRepository->get($cat->getId());
$level = $categoryObj->getLevel();
$arrow = str_repeat("---", $level-1);
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $subcategory) {
$this->categoryList[$subcategory->getEntityId()] = __($arrow.$subcategory->getName());
if($subcategory->hasChildren()) {
$this->renderSubCat($subcategory,$j);
}
}
return $this->categoryList;
}
}

Zend2 TableGateway: how to retrieve a set of data

I have a ContactsTable.php module and an function like this:
public function getContactsByLastName($last_name){
$rowset = $this->tableGateway->select(array('last_name' => $last_name));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row record");
}
return $row;
}
which is ok, but it only returns one row.
The problem is in my database I have multiple records with the same Last Name, so my question is:
How can I return a set of data?
I tried this:
$where = new Where();
$where->like('last_name', $last_name);
$resultSet = $this->tableGateway->select($where);
return $resultSet;
but it doesn't work.
Your first function should work as you expect, just remove line
$row = $rowset->current();
So, complete function should look like this:
public function getContactsByLastName($last_name){
$rowset = $this->tableGateway->select(array('last_name' => $last_name));
foreach ($rowset as $row) {
echo $row['id'] . PHP_EOL;
}
}
More info you can find in documentation http://framework.zend.com/manual/2.2/en/modules/zend.db.table-gateway.html
You can use the resultset to get array of rows:
public function getContactsByLastName($last_name) {
$select = new Select();
$select->from(array('u' => 'tbl_users'))
->where(array('u.last_name' => $last_name));
$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();
}
return $rows;
}
Its working for me.

Database expression not used in query

Can anyone tell me why my expression is not used in the query below?
SELECT accountreset.* FROM accountreset WHERE (reset_id = '34') LIMIT 1
public function findByResetId($resetId, $model = null) {
$result = null;
if (isset($resetId)) {
$select = $this->getDao()->select(
array('expiration' => new Zend_Db_Expr('UNIX_TIMESTAMP(expiration)'))
);
$select->where('reset_id = ?', $resetId);
$row = $this->getDao()->fetchRow($select);
if (null != $row) {
if (!($model instanceof Stage5_Model_PasswordResetter)) {
$model = new Stage5_Model_PasswordResetter();
}
// vul het model object
$model->setResetId($row->reset_id);
$model->setUserId($row->user_id);
$model->setExpiration($row->expiration);
$result = $model;
}
}
return $result;
}
Your Zend_Db_Expr should go into from() method instead of select()
$select = $this->getDao()
->select()
->from(
$this->getDao()->info('name'),
array('expiration' => new Zend_Db_Expr('UNIX_TIMESTAMP(expiration)'))
);

How to redirect to previous URL after login

I want to make redirection after login action to previous URL. Please tell me how to do that?
Store the page before Login into Session, After login , read the previous page url from the session and redirect the use to that page.
You can pass the "return" URL as a parameter to the login page. i.e http://yourserver.com/login/?return=http%3a%2f%2fyourserver.com%2fsomedir%2fsomething%2f. After a successful login you then use the get parameter to redirect by using a simple HTTP header location:http://yourserver.com/somedir/something/.
This is, for example, practiced in different Google and Microsoft services where there is a single page for signing in and different services that require the user to be loogged in.
You may this use Action helper I wrote some time ago. Cheers!
class Your_Controller_Action_Helper_GoBack
extends Zend_Controller_Action_Helper_Abstract
{
/**
* #todo Check if redirecting to the same domain
* #param bool $required Throw exception?
* #param bool $validateDomain
* #param bool $allowSubdomain
* #param string $alternative URL to redirect to when validation fails and required = true
* #param string $anchorParam Request parameter name which holds anchor name (#). Redirect to page fragment is not allowed according to HTTP protocol specification, but browsers do support it
* #throws Zend_Controller_Action_Exception if no referer is specified and $required == false or $checkdomain is true and domains do not match
*/
public function direct($required = true, $anchorParam = null, $validateDomain = true, $allowSubdomain = false, $alternative = null)
{
$front = Zend_Controller_Front::getInstance();
$request = $front->getRequest();
$referer = $request->getPost('http_referer');
if (empty($referer)) {
$referer = $request->getServer('HTTP_REFERER');
if (empty($referer)) {
$referer = $request->getParam('http_referer');
}
}
if (null === $alternative) {
$alternative = $request->getPost('http_referer');
if (null === $alternative) {
$alternative = $request->getParam('http_referer');
}
}
if ($referer) {
if ($validateDomain) {
if (!$this->validateDomain($referer, $allowSubdomain)) {
$this->_exception($alternative);
}
}
if (null != $anchorParam) {
$referer .= '#' . $request->getParam($anchorParam);
}
$redirector = new Zend_Controller_Action_Helper_Redirector();
$redirector->gotoUrl($referer);
} elseif($required) {
$this->_exception($alternative);
}
}
/**
* #throws Zend_Controller_Action_Exception With specified message
* #param string $message Exception message
* #param string $alternative
*/
private function _exception($alternative = null, $message = 'HTTP_REFERER is required.')
{
if ($alternative) {
if (Zend_Uri::check($alternative)) {
$redirector = new Zend_Controller_Action_Helper_Redirector();
$redirector->gotoUrl($alternative);
}
}
throw new Zend_Controller_Action_Exception($message);
}
/**
* Check if domain from current url and domain from specified url are the same
* #param string $url Target url
* #param string $allowSubdomain false
*/
public function validateDomain($url, $allowSubdomain = false)
{
if (!Zend_Uri::check($url)) {
return false;
}
$currentUri = $this->getCurrentUri();
$uri = Zend_Uri_Http::fromString($currentUri);
$currentDomain = $uri->getHost();
$uri = Zend_Uri_Http::fromString($url);
$target = $uri->getHost();
if ($allowSubdomain) {
// Find second dot from the end
$pos = strrpos($target, '.');
if (false !== $pos) {
$pos = strrpos(substr($target, 0, $pos), '.');
if (false !== $pos) {
$target = substr($target, $pos+1);
}
}
}
if ($target === $currentDomain) {
return true;
}
return false;
}
/**
* #return string Current URL
*/
public function getCurrentUri()
{
$request = $this->getRequest();
$path = $request->getRequestUri();
$server = $request->getServer();
$host = $request->getServer('HTTP_HOST');
$protocol = $request->getServer('SERVER_PROTOCOL');
if (!empty($protocol)) {
$protocol = explode('/', $protocol);
$protocol = strtolower($protocol[0]);
}
if (empty($protocol)) {
$protocol = 'http';
}
$baseUrl = $protocol . '://' . $host . '/';
$path = trim($path, '/\\');
$url = $baseUrl . $path;
return $url;
}
/**
* Like str_replace, but only once
* #param string $search
* #param string $replace
* #param string $subject
*/
public function replaceOnce($search, $replace, $subject)
{
$firstChar = strpos($subject, $search);
if($firstChar !== false) {
$beforeStr = substr($subject, 0, $firstChar);
$afterStr = substr($subject, $firstChar + strlen($search));
return $beforeStr . $replace . $afterStr;
} else {
return $subject;
}
}
}