SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from users where 0 = admin limit 1) - authentication

I try to make login for admin using ajax.But I run into this error.I don't know where is column 0 come from.
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where
clause' (SQL: select * from users where 0 = admin limit 1)
Here is my code
public function login()
{
$username= Input::get('username');
$password= Input::get('password');
$admin=array([
'username'=>$username,
'password'=>$password,
'level'=>1
]);
if ($this->auth->attempt($admin)) {
return "ok";
}
else {
return "fail";
}
}
Model
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
class User extends Model implements AuthenticatableContract
{
use Authenticatable;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ["username","password",'level'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password'];
public $timestamps = false;
}

The issue is your $admin array. You've mixed the two syntaxes for creating arrays and you've accidentally created an array of arrays.
You need to change your $admin array to either:
$admin = array(
'username'=>$username,
'password'=>$password,
'level'=>1
);
or:
$admin = [
'username'=>$username,
'password'=>$password,
'level'=>1
];

Related

Prestashop 1.7 - City field as dropdown or autocomplete

I am using Prestashop 1.7 and I need to change the city input field.
I have a billing software that only allows me to use predefined cities. So I have created a table ps_cities with the entries (id an city name).
I know how to write a dropdown or a autocomplete script, but I do not know where to change the input type in the Prestashop files.
On the 1.6 version you have the input field in a theme file, but somehow I fail to find in the new version.
In PrestaShop 1.7.7.X I've created a module that includes some new (and cool!) hooks like showing below. I consider this one a good option because it will be easier to maintain in the next PrestaShop releases.
Some assumptions here: I created a relationship model CityAddress with two fields id_city and id_address and a City model with fields like name, id_state, id_country, also I continued using Address::city string name for compatibility.
/**
* #see /classes/form/CustomerAddressFormatter.php#L156
* #param array $param [
* #var array $fields
* ]
*/
public function hookAdditionalCustomerAddressFields($params)
{
($params['fields']['city'])->setType('hidden');
// New field
$formField = $params['fields'];
$formField = (new FormField())
->setName('id_city')
->setLabel($this->l('City'))
->setRequired(true)
->setType('select')
;
// If an address already exits, select the default city
if (Tools::getIsset('id_address')) {
$address = new Address(Tools::getValue('id_address'));
if (!empty($address->id_state)) {
$cities = City::getCitiesByIdState((int) $address->id_state);
if (!empty($cities)) {
foreach ($cities as $city) {
$formField->addAvailableValue(
$city['id_city'],
$city['name']
);
}
$id_city = CityAddress::getIdCityByIdAddress((int) $address->id);
$formField->setValue($id_city);
}
}
}
// Add the id_city field in the position of the city field
$keys = array_keys($params['fields']);
$search = 'city';
foreach ($keys as $key => $value) {
if ($value == $search) {
break;
}
}
$part1 = array_slice($params['fields'], 0, $key + 1);
$part2 = array_slice($params['fields'], $key + 1);
$part1['id_city'] = $formField;
$params['fields'] = array_merge($part1, $part2);
}
This one to validate the field:
/**
* #see /classes/form/CustomerAddressForm.php#L123
* #param array $param [
* #var CustomerAddressForm $form
* ]
*/
public function hookActionValidateCustomerAddressForm($params)
{
if (empty(Tools::getValue('id_city'))
|| empty(Tools::getValue('city'))) {
return false;
}
$form = $params['form'];
$idCityField = $form->getField('id_city');
$idCity = (int) Tools::getValue('id_city');
$cityObj = new City($idCity);
$city = pSQL(Tools::getValue('city'));
if ($cityObj->name !== $city) {
$idCityField->addError(sprintf(
$this->l('Invalid name in field id_city %s and city %s'),
$cityObj->name,
$city
));
return false;
}
return true;
}
And the submitted field:
/**
* #see /classes/form/CustomerAddressForm.php#L153
* #param array $param [
* #var Address $address
* ]
*/
public function hookActionSubmitCustomerAddressForm($params)
{
/** #var Address */
$address = $params['address'];
$address->save();
if (!Validate::isLoadedObject($address)) {
throw new PrestaShopException($this->l('Address object error while trying to save city'));
}
// If address has a previous value then update it
$cityAddress = CityAddress::getCityAddressByIdAddress((int) $address->id);
$city = City::getCityByNameAndIdState($address->city, $address->id_state);
$cityAddress->id_city = $city->id;
$cityAddress->id_address = $address->id;
$cityAddress->save();
}
It is possible if you have this line in the additionalCustomerAddressFields hook:
https://github.com/PrestaShop/PrestaShop/blob/develop/classes/form/CustomerAddressFormatter.php#L150
For previous version I included ['fields' => &$format] as a parameter.
You can find all form fields of the Front Office in your theme's /templates/_partials/form-fields.tpl file

Doctrine 2 association mapping always returns null

I'm having an issue getting an association to populate in my Doctrine entity. The entity gets populated fully with the single exception of the association, even when set to eager loading. I have other similar associations working so I suspect there is some fundamental understanding that I'm missing here.
What I am trying to do here is populate $s in the entity with the S object, known as s in the query. I apologize in advance for the naming, but I've had to strip out anything potentially identifying as this is part of proprietary code.
Here's the bulk of my SHealth entity class:
// -------------------------------------------------------------------
// ENTITY FOR SHealth
// -------------------------------------------------------------------
/**
* Used for tracking the current health of shares.
* #Entity(repositoryClass="SHealthRepository")
* #Table(name="s_health")
*/
class SHealth
{
/**
* #Id
* #Column(type="integer", name="s_id")
*/
protected $sId;
/**
* #Id
* #Column(type="integer", name="l_id")
*/
protected $lId;
/**
* #Id
* #Column(type="smallint", name="s_type")
*/
protected $sType;
/**
* #Id
* #Column(type="smallint", name="s_subtype")
*/
protected $sSubtype;
/**
* #Column(type="smallint", name="health_status")
*/
protected $healthStatus;
/**
* #Column(type="datetime", name="update_time")
*/
protected $updateTime;
/**
* Scalar value
*/
protected $active;
/**
* #ManyToOne(targetEntity="S")
* #JoinColumns({
* #JoinColumn(name="l_id", referencedColumnName="l_id"),
* #JoinColumn(name="s_id", referencedColumnName="id")
* })
*/
protected $s;
// [Accessors and mutators omitted]
}
Here's a snippet of the associated repository class:
// -------------------------------------------------------------------
// Repository fetch function
// -------------------------------------------------------------------
$rtime_check = !$include_rtimed ? " AND s.rtime IS NULL" : "";
$limit_check = $limit > 0 ? " LIMIT " . $limit : "";
$sql = "SELECT
s.l_id,
s.id AS s_id,
COALESCE(s_health.s_type, s.type) AS s_type,
COALESCE(s_health.s_subtype, 0) AS s_subtype,
s_health.health_status,
s_health.update_time,
(s.enabled AND
COALESCE(orsr.status, orsh.status, 0) > 0) AS active
FROM s
LEFT JOIN s_health ON
s.l_id = s_health.l_id AND
s.id = s_health.s_id AND
s.type = s_health.s_type AND
s_health.s_subtype = 0
LEFT JOIN orsr ON
s.l_id = orsr.l_id AND
s.se_id = orsr.se_id AND
orsr.status IN ([omitted])
LEFT JOIN orsh ON
s.l_id = orsh.l_id AND
s.id = orsh.s_id AND
orsh.status IN ([omitted])
WHERE s.l_id IN (:d_ids)
{$rtime_check}
GROUP BY s.l_id, s.id
{$limit_check}";
// Map the SQL result columns to class properties.
$rsm = new ResultSetMappingBuilder($this->_em);
$rsm->addRootEntityFromClassMetadata(SHealth::class, 's_alias');
$rsm->addScalarResult('active', 'active');
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter("d_ids", $d_ids);
$results = $query->getResult();
// Inject aggregate function results into the resulting object.
$health_objects = [];
foreach ($results as $result)
{
$health_object = $result[0];
$health_object->setActive($result['active']);
$health_objects[] = $health_object;
}
return $health_objects;
Finally, here's the S class, with some members removed:
// -------------------------------------------------------------------
// ENTITY FOR S
// -------------------------------------------------------------------
/**
* #Entity
* #Table(name="s")
*/
class S
{
/**
* #Id
* #Column(type="integer")
*/
protected $id;
/**
* #Id
* #Column(type="integer", name="l_id")
*/
protected $lId;
/**
* #Column(type="integer", name="se_id")
*/
protected $seId;
/**
* #Column(type="smallint")
*/
protected $type;
/**
* #Column(type="boolean")
*/
protected $enabled;
/**
* #Column(type="datetime")
*/
protected $rtime;
// [Accessors and mutators omitted]
}
I have all of the necessary getters and setters, and all the necessary database data is present in both tables so there shouldn't be any issue with the join columns.
If your joined columns are part of the entity identifier, you should try once like this:
1) Mark the association as part of identifier with an #Id annotation:
/**
* #Id
* #ManyToOne(targetEntity="S")
* #JoinColumns({
* #JoinColumn(name="l_id", referencedColumnName="l_id"),
* #JoinColumn(name="s_id", referencedColumnName="id")
* })
*/
protected $s;
2) remove the other two columns:
/**
* #Id
* #Column(type="integer", name="s_id")
*/
protected $sId;
/**
* #Id
* #Column(type="integer", name="l_id")
*/
protected $lId;
I'm still not fully sure what prevented the native query from working, but I've changed direction in solving this problem. I'm posting as an answer in the slim chance someone else will have a similar problem in the future.
What I wound up doing was scrapping the SHealth repository entirely, and instead I am simply using an S repository. I went this route because my native query was selecting from s primarily anyway. So, instead of trying to put the results of a select from and join s onto the sHealth entity (using a native query), I used a simpler DQL query from the other side of the relationship.
The following is my new repository fetch function, this time in the S repository, which achieves essentially the same thing as my native query in the question:
$query_builder = $this->_em->createQueryBuilder();
$query_builder->select('s, CASE WHEN s.enabled = TRUE AND COALESCE(orsr.status, orsh.status, 0) != 0 THEN TRUE ELSE FALSE END AS active')
->from(S::class, 's')
->leftJoin(
ORSR::class,
'orsr',
\Doctrine\ORM\Query\Expr\Join::WITH,
"s.lId = orsr.lId AND
s.seId = orsr.seId AND
orsr.status IN ([omitted])"
)
->leftJoin(
ORSH::class,
'orsh',
\Doctrine\ORM\Query\Expr\Join::WITH,
"s.lId = orsh.lId AND
s.id = orsh.sId AND
orsh.status IN ([omitted])"
)
->where('s.lId IN (:d_ids)')
->setParameter('d_ids', $d_ids);
// If rtimed items were not requested, exclude them.
if (!$include_rtimed)
{
$query_builder->andWhere(
$query_builder->expr()->isNull('s.rtime')
);
}
// Apply limit if specified.
if (!is_null($limit))
{
$query_builder->setMaxResults($limit);
}
$s_list = $query_builder->getQuery()->getResult();
// Inject aggregate function results into the resulting object.
$results = [];
foreach ($s_list as $row)
{
$this_s = $row[0];
$this_s->setActive($row['active']);
$results[] = $this_s;
}
return $results;
I added this field to my S entity:
/**
* #OneToMany(targetEntity="SHealth", mappedBy="s")
* #JoinColumns({
* #JoinColumn(name="l_id", referencedColumnName="l_id"),
* #JoinColumn(name="id", referencedColumnName="s_id")
* })
*/
protected $health;
And, I altered sHealth's association to inverse the one in S:
/**
* #ManyToOne(targetEntity="S", inversedBy="health")
* #JoinColumns({
* #JoinColumn(name="l_id", referencedColumnName="l_id"),
* #JoinColumn(name="s_id", referencedColumnName="id")
* })
*/
protected $s;
The moral of the story is that instead of trying to perform a right join for an association using a native query, it may be beneficial to reverse the entities and left join (in this case via association using DQL) instead.

Zend_Db_Adapter_Abstract::update() must be an array

I am having some trouble updating a row.
My class is extending Zend_Db_Table_Abstract
Here is my code:
return $this->update(
array('data' => $data),
$this->getAdapter()->quoteInto("id = ?", $id)
) ? true : false;
The exception I keep getting is:
PHP Catchable fatal error: Argument 2 passed to Zend_Db_Adapter_Abstract::update() must be an array, string given, called in /Applications/MAMP/htdocs/app/library/Session/Handler.php on line 51 and defined in /Applications/MAMP/libraries/zend-framework/ZendFramework-1.11.3-minimal/library/Zend/Db/Adapter/Abstract.php on line 587
I tried passing it an array also but nothing happens. Any idea?!
You may use array in second argument of ->update()
example:
$this->update(
array('data' => $data),
array("id = ?" => $id),
) ? true : false;
but the string must be ok
becouse
/**
* Convert an array, string, or Zend_Db_Expr object
* into a string to put in a WHERE clause.
*
* #param mixed $where
* #return string
*/
protected function _whereExpr($where)
{
if (empty($where)) {
return $where;
}
**if (!is_array($where)) {**
$where = array($where);
}

How can i load model in joomla?

This is my Controller
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.application.component.controller');
/**
* Hello World Component Controller
*
* #package Joomla.Tutorials
* #subpackage Components
*/
class HelloController extends JController
{
/**
* Method to display the view
*
* #access public
*/
function __construct($default = array())
{
parent::__construct($default);
// Register Extra tasks
$this->registerTask( 'detail' , 'display' );
}
function display()
{
switch($this->getTask())
{
case 'detail' :
{
JRequest::setVar( 'view' , 'new');
// Checkout the weblink
$model = $this->getModel('hello');
} break;
}
parent::display();
}
}
this is my view.html.php
class HelloViewNew extends JView
{
function display($tpl = null)
{
global $mainframe;
$db =& JFactory::getDBO();
$model =& $this->getModel('hello');
$items = & $model->getdetail();
$this->assignRef( 'items', $items );
parent::display($tpl);
}
}
and this is my model
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.model' );
/**
* Hello Model
*
* #package Joomla.Tutorials
* #subpackage Components
*/
class HelloModelHello extends JModel
{
/**
* Gets the greeting
* #return string The greeting to be displayed to the user
*/
var $_data;
/**
* Returns the query
* #return string The query to be used to retrieve the rows from the database
*/
function _buildQuery()
{
$query = ' SELECT * '
. ' FROM #__hello WHERE published = 1'
;
return $query;
}
/**
* Retrieves the hello data
* #return array Array of objects containing the data from the database
*/
function getData()
{
// Lets load the data if it doesn't already exist
if (empty( $this->_data ))
{
$query = $this->_buildQuery();
$this->_data = $this->_getList( $query );
}
//echo "<pre>"; print_r($this->_data); exit;
return $this->_data;
}
function detail()
{
echo "this is test"; exit;
}
}
My question is how can i fetch that detail function from database its not working for me?
on your model, you've the function : function detail() ,
But you've tried to call the function on view with : $items = & $model->getdetail();
Remember your function is detail() NOT getdetail() . So, call with :
$items = & $model->detail();
That's your only mistake I guess so, good luck
you should use this in contoller
$view = $this->getView();
$view->setModel($this->getModel());
then you can use $this->getModel() in view.

How do I only show fields that have values, and hide fields that do not have values?

I am trying to get this code to show only fields that have values, any fields that don't have values are not meant to be displayed. It doesnt seem to be working
Any idea what I am doing wrong?
My simple test form is here http://www.healthybrighton.co.uk/wse/node/1844
/**
* Build a table of submitted values
*
* #param $form_vals array Submitted form data
* #param $select_mapping array Map select components to their value|label chocies
* #return HTML of the themed table
*/
function _format_form_state($form_vals = array(), $select_mapping) {
$output = '';
$header = array();
$rows = array();
if (!empty($form_vals)) {
foreach ($form_vals as $component_name => $component_value) {
$rows = array_merge(
$rows,
_add_component_row(
$component_name,
$component_value,
0,
$select_mapping
)
);
}
}
$output .= theme('table', $header, $rows);
return $output;
}
/**
* Build a table of submitted values
*
* #param $select_mapping array Map select components to their value|label chocies
* #param $values array Submitted form data
* #return HTML of the themed table
*/
function _format_form_state($select_mapping, $values = array()) {
$header = array(t('First'), t('Second'), t('Third'), t('Fourth'));
$rows = array();
foreach ($values as $cname => $cval) {
$rows[] = array($cname, $cval, 0, $select_mapping);
}
return theme_table($header, $rows);
}
$select_mapping should be first argument in function.
Argument with default value should not be preceded by argument without a default value.