How to query below in zend 2
select * from states st where TRIM(LOWER(st.state_name))='noida'
Any help is appreciated.
Thanks
/* DB Adapter get and SQL object create */
$adapter = GlobalAdapterFeature::getStaticAdapter();
$sql = new \Zend\Db\Sql\Sql($adapter);
/* Select object create */
$select = new \Zend\Db\Sql\Select();
$select->from('states');
$select->where->addPredicate(
new \Zend\Db\Sql\Predicate\Expression(
'TRIM(LOWER(state_name)) = ?',
'noida'
)
);
/* Select object convert to string and execute */
$queryString = $sql->getSqlStringForSqlObject($select);
$result = $adapter->query($queryString, Adapter::QUERY_MODE_EXECUTE);
Use following:
$resultStates=$this->states->select()->where('TRIM(LOWER(st.state_name))=?','noida')
->query()
->fetchAll();
For details refer Here and Here.
In you model file just use below code here I am using module profile.
Profile/Model/Common.php
namespace Profile\Model;
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
class Common
{
protected $dbConfig;
protected $adapter;
public function __construct($dbConfig)
{
$this->adapter = new Adapter($dbConfig);
}
public function getStateList()
{
$sql = "select * from states st where TRIM(LOWER(st.state_name))='noida'";
$statement = $this->adapter->query($sql);
$results = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($results);
$list = $resultSet->toArray();
return $list; // This will return a list of array
}
}
Profile/Controller/IndexController
namespace Profile\Controller;
use Profile\Model\Common;
class IndexController extends AbstractActionController
{
protected $dbConfig = array(
'driver' => DRIVER,
'database' => DB,
'username' => DBUSER,
'password' => DBPASS
);
public function init(){
$ssOrder = new Container(__CLASS__);
//SET OPTIONS
}
public function indexAction()
{
$plist = new Common($this->dbConfig);
$resultList = $plist->getStateList(); // This will give you state list
}
}
Good Luck
Related
I need how to show data in another table like MySQL join or something like that
MySQL example
My Code
Model usuarios
class Usuario extends Model {
protected $table = 'usuarios';
protected $primaryKey = 'idusuarios';
protected $filliable = [
'cedula', 'nombre', 'tele1', 'tele2', 'correo', 'direccion',
'user_name', 'user_pass', 'fecha_ingreso', 'usu_idrol'
];
public function Usuario() {
return $this->hasOne('app\Roles','idrole','usu_idrol','desc_rol');
}
const CREATED_AT = NULL;
const UPDATED_AT = NULL;
}
Model Roles
class Roles extends Model {
protected $table ='roles';
protected $primarykey = 'idrole';
protected $filliable = ['desc_rol'];
public function Roles() {
return $this->belongsTo('app\Usuario', 'usu_idrol', 'idrole');
}
}
Controller usuarios
public function index(Request $request) {
if (!$request->ajax()) return redirect('/');
$usuarios = Usuario::all();
return $usuarios;
}
View usuarios
that's what I need
Try this in the controller that is returning data to your vue instance
//get all the users from the database (in your controller)
//you need to create a new array so as to easily map the role in the returned results
return Usuario::with('Usuario')->get()->map(function($role) {
return [
'field1' => $role->field1,
'field2' => $role->field2,
'field3' => $role->field3,
'field4' => $role->field4,
'field5' => $role->field5,
'rol' => $role->Usuario->desc_role
];
});
I'm making a social network's login page but when I login a get the error above. My db.php is (i use pdo):
<?php
class DB {
private static function connect() {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=social;charset=utf8', 'danny', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
?>
Called from
$user_id = DB::query('SELECT id
FROM users
WHERE email=:email')[0]['id'];
DB::query('INSERT INTO login_tokens
VALUES(\'\', :token, :user_id)',
array(':token'=>sha1($token), ':user_id'=>$user_id));
Your class has many issues. to fix them:
class DB {
protected static $pdo;
public static function connect() {
static::$pdo = new PDO('mysql:host=127.0.0.1;dbname=social;charset=utf8', 'danny', 'Dani2034');
static::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function query($query, $params = array()) {
$statement = self::$pdo->prepare($query);
$statement->execute($params);
return $statement;
}
}
DB::connect(); // called only once
$user_id = DB::query('SELECT id FROM users WHERE email=?', array($email))->fetchColumn();
DB::query('INSERT INTO login_tokens VALUES(null, ?, ?)', array(sha1($token), $user_id));
I need some help with SF 2.7 serializer
I have made an API with get Json Data like this :
{
"dateDebut":"2017-02-16",
"dateFin":"2018-02-16",
"caMoisTotalHorsSessions":"5.2",
"caMoisClients":"5.3",
"caMoisGarantie":"5.4",
"caMoisHuile":"5.5" }
I tried many way in order to deserialze into my object Class where dateDebut and dateFin are attending to be Datetime object and not string
try {
$encoder = new JsonEncoder();
$normalizer = new GetSetMethodNormalizer();
$callback = function ($date) {
return new \DateTime($date);
};
$normalizer->setCallbacks(array(
'dateDebut' => $callback,
'dateFin' => $callback, ));
$serializer = new Serializer(array($normalizer), array($encoder));
$entity = $serializer->deserialize($request->getContent(), $class, $format);
} catch (RuntimeException $e) {
return new JsonResponse(
['code' => Response::HTTP_BAD_REQUEST, 'message' => $this->trans('api.message.data_error')],
Response::HTTP_BAD_REQUEST);
}
But callbacks are never used :/ Could anyone help me please ?
Aim is to transform date string into Datetime object automatically before flush the object in database.
Thanks a lot
What you are trying to do is denormalization. The normalizer callbacks are for normalization. I think it's pretty confusing. It's strange that they would offer setting callback for just one direction.
I tested some code doing what I think you want to do. You need a custom normalizer class. The class is not so complicated, it can extend from the GetSetNormalizer or the ObjectNormalizer. You just want to create the \DateTime inside here, and you might add some validation for the date time.
class BoardNormalizer extends GetSetMethodNormalizer
{
public function denormalize($data, $class, $format = null, array $context = array())
{
if (isset($data['created'])) {
$data['created'] = new \DateTime($data['created']);
}
return parent::denormalize($data, $class, $format, $context);
}
}
I tested it with this code:
$json = json_encode([
'created' => '2017-02-20T05:49:51-0500'
]);
$encoder = new JsonEncoder();
$normalizer = new MyCustomNormalizer();
$serializer = new Serializer([$normalizer], [$encoder]);
$entity = $serializer->deserialize($json, MyCustomClass::class, 'json');
And it produced my custom class where the created property was a \DateTime object.
Aim is to transform date string into Datetime object automatically before flush the object in database.
Something like this? Using setters/getters ? I'm using the following code in entity
private $created;
public function setCreated($created)
{
if (!($created instanceof \DateTime)) {
$created = date_create($created);
}
$this->created = $created;
return $this;
}
what is the professional way insert record in database.
i am using laravel 5.2.
i'm new in laravel.
class students extends Controller
{
public function index()
{
$insertData = array(
"name" => Input::get("name"),
"detail" => Input::get("detail"),
"token_key" => Input::get("_token")
);
return view('student');
}
public function fees()
{
$record = array(
"p_name" => Input::get("name"),
"p_fees" => Input::get("fees"),
"p_detail" => Input::get("detail")
);
return view('fee');
}
}
stander able way?
You should use mass assignment. Fill $fillable array inside your model and use this:
Model::create($insertData);
public function store_student(Request $request)
{
$student = new Student;
$student->name = $request->name;
$student->detail = $request->details
$student->save();
return view('student');
}
public function store_fee(Request $request)
{
$fee = new Fee;
$fee->p_name = $request->name;
$fee->p_fee = $request->fees;
$fee->p_detail = $request->details
$fee->save();
return view('fee');
}
I suggest you to read this from Laravel official guide.
However you can do it like this:
DB::table('tablename')->insert($insertData);
I want to understand why this works perfect with out a problem.
$this->db = Zend_Db_Table_Abstract::getDefaultAdapter();
public function getMessages()
{
$select = $this->db->select();
$select
->from('Mail_Text', '*')
->join(
array('Mail' => 'Mail'),
'Mail.id = Mail_Text.parent_id', '*'
);
return $this->db->fetchAll($select);
}
Now if I do this by extending Zend_Db_Table_Abstract
class Mail_Model_Text extends Zend_Db_Table_Abstract
{
protected $_name = 'Mail_Text';
public function fetchMessges(){
$select = $this->select();
$select->setIntegrityCheck(false)
->from($this->_name, '*')
->join(
array('Mail' => 'Mail'),
'Mail.id = Mail_Text.parent_id', '*'
);
return $this->fetchAll($select);
}
}
This crashes MySql I wanted to keep the code separate but I can join theses tables. All the Single select and updates query's work perfect. I have research all over the net and can't seem to find the solution to this puzzle. Any Help to his would be great Thanks in advance.
You don't need the from() statement or need to alias the table to the same name:
class Mail_Model_Text extends Zend_Db_Table_Abstract
{
protected $_name = 'Mail_Text';
public function fetchMessges()
{
$select = $this->select();
$select->setIntegrityCheck(false)
->join('Mail', 'Mail.id = Mail_Text.parent_id');
return $this->fetchAll($select);
}
}
Also, ensure that you have correctly indexed your tables.