Zend insert user and set value to max()+1 - zend-framework

My code:
public function insertMember($member)
{
$maxOrderNumber = $this->select()
->from($this, array(new Zend_Db_Expr('max(order_number)')));
$id = $this->insert($member, $maxOrderNumber);
return $id;
}
I want to insert member to last position in members table and order_number entity. Tried with $maxOrderNumber but i keep getting 0 value in database.
Im using MySql. Also i have user_id with (AI) Autoincrement so i'm forced to function this way.

public function insertMember($member)
{
$maxOrderNumber = $this->select()
->from($this, array(new Zend_Db_Expr('max(order_number)')));
$stmt = $maxOrderNumber ->query();
$result = $stmt->fetchAll();
$id = $this->insert($member, $result ['order_number']);
return $id;
}
soemthing like that...

Related

syntax for selecting the last recordset in my model

I tried different possibilities but nothing worked, in the tutorial I couldn't find an example either.
I have a method in my modelclass:
public function getlastImport($filename)
{
//$id = (int) $id;
$rowset = $this->tableGateway->select(['Path' => $filename]);
$row = $rowset->current();
if (! $row) {
throw new RuntimeException(sprintf(
'Could not find row with identifier %d',
$id
));
}
return $row;
}
I want to retrieve the last import of a given filename, so ist must be like in sql:
select max(ID) from table where filename = $filename;
But how would be the right syntax in this case?
The sql query should be
"SELECT * FROM table_name WHERE filename={$filename} ORDER BY id DESC LIMIT 1"
Use as the following in your model
public function getlastImport($filename)
{
$select = $this->tableGateway->getSql()->select();
$select->columns(array('id', 'filename', 'label'));
$select->where(array('filename' => $filename));
$select->order("id DESC");
$select->limit(1);
$result = $this->tableGateway->selectWith($select);
$row = $result->current();
if (! $row) {
throw new RuntimeException(sprintf(
'Could not find row with identifier %d',
$id
));
}
return $row;
}
Hope this would help you!

Filter information and custom repository with Symfony2?

From GET parameters, I want to get information from my entities.
In my view I created a form with 3 selects (not multiple ones), like this:
http://pix.toile-libre.org/upload/original/1393414663.png
If I filter only by user I got this in the url: ?category=0&user=6&status=0
I'll have to handle the 0 values...
This form used to filter my tasks.
This is a part of my action in my controller:
if($request->query->has('user')) {
$category_id = $request->query->get('category');
$user_id = $request->query->get('user');
$status_id = $request->query->get('status');
// A little test to see if it works.
echo $category_id . '<br>' . $user_id . '<br>' . $status_id;
// I will pass these variables to a repository
$tasks = $em->getRepository('LanCrmBundle:Task')->findFiltered($category_id, $user_id, $status_id);
} else {
$tasks = $em->getRepository('LanCrmBundle:Task')->findAll();
}
I create a repository with this method:
public function findFiltered($category_id, $user_id, $status_id)
{
/**
* Get filtered tasks.
*
* Get only title, priority, created_at, category_id, user_id and status_id fields (optimization)
*
* Where field category_id = $category_id unless $category_id is smaller than 1 (not secure enough)
* Where field user_id = $user_id unless $user_id is smaller than 1 (not secure enough)
* Where field status_id = $status_id unless $status_id is smaller than 1 (not secure enough)
* Should I do these tests here or in the controller?
*/
}
How to do this query ? Do you have any other elegant suggestions to solve this problem?
You can try:
public function findFiltered($category_id, $user_id, $status_id)
{
$queryBuilder = $this->createQueryBuilder('t');
if(!empty($category_id) && is_numeric($category_id)) {
$queryBuilder->andWhere('t.category = :category')->setParameter('category', $category_id);
}
if(!empty($user_id) && is_numeric($user_id)) {
$queryBuilder->andWhere('t.user = :user')->setParameter('user', $user_id);
}
if(!empty($status_id) && is_numeric($status_id)) {
$queryBuilder->andWhere('t.status = :status')->setParameter('status', $status_id);
}
return $queryBuilder->getQuery()->getResult();
}

$this->fetchRow creates failure in phpunit in Zend framework

I followed Rob Allens ZF 1 Tutorial and wanted to pimp it up with some UnitTesting. But whenever I run the phpunit command, i get the message:
here was 1 failure:
1) IndexControllerTest::testDeleteAction
Failed asserting last controller used <"error"> was "Index"
/path/to/library/Zend/Test/PHPUnit/ControllerTestCase.php:1000
/path/to/tests/application/controllers/IndexControllerTest.php:55
FAILURES!
Tests: 4, Assertions: 9, Failures: 1.
The Action in question is the deleteAction and looks like this:
public function deleteAction() {
if ($this->getRequest()->isPost()) {
$del = $this->getRequest()->getPost('del');
if ($del == 'Yes') {
$id = $this->getRequest()->getPost('id');
$wishes = new Application_Model_DbTable_Wishes();
$wishes->deleteWish($id);
}
$this->_helper->redirector('index');
}
else {
$id = $this->_getParam('id', 0);
$wishes = new Application_Model_DbTable_Wishes();
$this->view->wish = $wishes->getWish($id);
}
}
I tracked the error down to be $wishes>getWish($id); so if i go to that function, that looks like this:
public function getWish($id) {
$id = (int) $id;
$row = $this->fetchRow('id = ' . $id);
if(!$row){
throw new Exception("Could not find row $id");
}
return $row->toArray();
}
it appears the line $row = $this->fetchRow('id = ' . $id); causes the problem. And I can't figure out why. All action work just fine, they do as expected.Any idea how to fix this?
Thanks!
Maybe try using the select() object instead if a plain string:
public function getWish($id) {
$id = (int) $id;
$select = $this->select();
$select->where('id = ?', $id);
$row = $this->fetchRow($select);
if(!$row){
throw new Exception("Could not find row $id");
}
return $row->toArray();
}
This just a wild guess, but who knows. The only thing that looks at all odd is the lack of a placeholder in the query string (?).
FetchRow() does like to work with the select() object, in fact if you pass a string the first thing fetchRow() does is build a select(). So maybe it just doesn't like the string.

Incorrect `update statement` using IN operator with Zend

I have a function which is wanted to execute a statement like below:
UPDATE coupon_users SET status = status | '1' WHERE id IN ('3','4')
And in coupon_users model, I wrote a method like below do to:
/**
* #param array $ids #array(3,4)
* #param array $status #1
*/
public function updateStatus(array $ids, $status)
{
$result = $this->_db->query(
"UPDATE {$this->_name} SET status = status | ? WHERE id IN (?)",
array(
$status,
$ids
)
)->execute();
return $result;
}
But the query is always:
UPDATE coupon_users SET status = status | '1' WHERE id IN ('Array')
I don't know what am I wrong here, please help me, many thanks.
According to the PDO documentation (Zend_Db uses PDO as its DB access backend):
You cannot bind multiple values to a single named parameter in, for
example, the IN() clause of an SQL statement.
So, you'll probably need to prepare a bit further your query, so that it contains as many markers as elements in the array. A possible solution could be the following:
// Compose the query
$queryToExecute = "UPDATE {$this->_name} SET status = status | ? WHERE id IN (";
$questionMarks = array();
for ($id in $ids) {
$questionMarks[] = '?';
}
$queryToExecute .= implode(',', $questionMarks);
$queryToExecute .= ')';
// $queryToExecute should have the format "UPDATE ... WHERE id IN (?,?,?,...?)"
// Execute it
$result = $this->_db->query(
$queryToExecute,
array($status, $ids)
)->execute();
Hope that helps,
try:
public function updateStatus(array $ids, $status)
{
$result = $this->_db->query(
"UPDATE {$this->_name} SET status = ? WHERE id IN (?)",
array(
$status,
implode(',',$ids)
)
)->execute();
return $result;
}
Update:
Have you tried?:
$this->_db->update($this->_name, array('status'=>$status), array('id IN (?)'=>$ids));
I haven't tested it, it also depends on what $this->_db is an instance of
http://framework.zend.com/manual/en/zend.db.adapter.html#zend.db.adapter.write.update
Try this..
public function updateStatus(array $ids, $status)
{
$inarray= implode(',',$ids);
$result = $this->_db->query(
"UPDATE {$this->_name} SET status = status | ? WHERE id IN (?)",
array(
$status,
$inarray
)
)->execute();
return $result;
}
Its working fine for me.
$existingImagesIds = array(1, 2, 3, 7);
$where = $pImgModel->getAdapter()->quoteInto("id in (?) ", $existingImagesIds);
$pImgModel->update(array('status' => '0'), $where);

Zend get foreign ID from login table

I am using Zend and Doctrine to login using a table containing also a foreign ID to another table. I need to get this ID in order to use it in a Doctrine query (through the controller) to the database like this:
$q = Doctrine_Query::create()
->from('Lost_Model_Item i')
->where('i.StatID = ?', 'I need the ID here')
$result = $q->fetchArray();
I have tried to get it like this:
Zend_Auth::getInstance()->getIdentity()->ID
But it seems to not work. I am new to Zend and a bit lost here. Could you please help?
As I ma working with doctrine I have created an adapter as follow:
public function authenticate()
{
$q = Doctrine_Query::create()
->from('Lost_Model_Station u')
->where('u.username = ? AND u.password = MD5(?)',
array($this->username, $this->password)
);
$result = $q->fetchArray();
if (count($result) == 1) {
$this->_resultArray = $result[0];
return new Zend_Auth_Result(
Zend_Auth_Result::SUCCESS, $this->username, array());
} else {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE, null,
array('Authentication unsuccessful')
);
}
}
How about using getIdentity to get the username and then use a sql join on Lost_Model_Item and Lost_Model_Station
$q = Doctrine_Query::create()
->from('Lost_Model_Item i')
->leftJoin('i.Lost_Model_Station u')
->where('u.username = ?', Zend_Auth::getInstance()->getIdentity())
$result = $q->fetchArray();
This assumes that there is a doctrine "hasOne" relation defined for Lost_Model_Station (in the base class):
public function setUp()
{
parent::setUp();
$this->hasOne('Lost_Model_Item', array(
'local' => 'StatID',
'foreign' => 'whatever_id_StatID_relates_to'));
}
Zend_Auth::getInstance()->getIdentity()->ID
well you got what you store in Identity . You need to post the code where you ask user to login . Because there you are not storing the ID inside the session storage which Zend_Auth uses . Basically do this there
$row = $this->_adapter->getResultRowObject();
Zend_Auth::getInstance()->getStorage()->write($row);
where $this->_adapter is
$this->_adapter = new Zend_Auth_Adapter_DbTable();
$this->_adapter->setTableName('users')
->setIdentityColumn('email')
->setCredentialColumn('password');