syntax for selecting the last recordset in my model - zend-framework

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!

Related

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

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...

Perl Hypertable mutator exception

I am using Hypertable::ThriftClient, and using mutator for mass insertion. Here is the code sample: $master, $port and $namespace are all defined.
Table:
show create table users; # Table schema is below
CREATE TABLE GROUP_COMMIT_INTERVAL "100" users (
'column_name_fake' MAX_VERSIONS 1,
ACCESS GROUP audience ('column_name_fake'),
)
:hypertable$ SELECT * FROM users limit 1; # displays
2342345 sf_following:1000234
2342346 sf_following:1234234
Code:
my $ht = new Hypertable::ThriftClient($master, $port);
my $ns = $ht->namespace_open($namespace);
my $users_mutator = $ht->mutator_open($ns, 'table_name', 2);
Subroutine:
sub batch_insert {
my ($ht, $mutator, $column_family, $row, $val) = #_;
my $keys;
my $cell;
try {
$keys = new Hypertable::ThriftGen::Key({
row => $row,
column_family => $column_family });
$cell = new Hypertable::ThriftGen::Cell({key => $keys, value => $val});
}
catch {
warn Dumper({ 'Error' => $_ });
};
$ht->mutator_set_cell($mutator, $cell);
$ht->mutator_flush($mutator);
return 1;
}
Function called:
for(.....) { # Just for example
batch_insert($ht, $users_mutator, '', $fs, "node:$node_u");
}
Here I get an exception,
Hypertable::ThriftGen::ClientException=HASH(0x54d7380)
Can anyone clarify, why?
Edit: I added table structure for more clarity?
The ClientException class is defined as follows:
exception ClientException {
1: i32 code
2: string message
}
Try catching the exception and printing out the code (in hex) and message. That should help pinpoint what's going on.
FIX: So, this exception is raised is a required parameter 'column_qualifier' was not
passed as per the table design. See below:
sub batch_insert {
my ($ht, $mutator, $cf, $cq, $row, $val) = #_;
my $keys = new Hypertable::ThriftGen::Key({
row => $row,
column_family => $cf,
column_qualifier => $cq });
my $cell = new Hypertable::ThriftGen::Cell({key => $keys, value => $val});
$ht->mutator_set_cell($mutator, $cell);
#$ht->mutator_flush($mutator);
}
Calling the above function:
--------------------------
batch_insert($ht, $users_mutator, 'column_family' , 'column_qualifier, 'row_key', '');
and it worked like a charm. If you are in similar types of issues, Let me know, I can help out. I spent quite a bit of time, reading about the Thrift api.

$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);

insert_id mysqli

I'm trying to return the inserted id from a mysql INSERT query. Each time I run the function I get 0 as the result. Can someone please explain at what point I can retrieve the value because although the script below executes I cannot retireve the inserted id. Probably done something stupid.
<?php
public function execSQL($sql, $params, $close){
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$stmt = $mysqli->prepare($sql) or die ("Failed to prepared the statement!");
call_user_func_array(array($stmt, 'bind_param'), $this->refValues($params));
$this->insert_id($this->connection);
$stmt->execute();
if($close){
$result = $mysqli->affected_rows;
} else {
$meta = $stmt->result_metadata();
while ( $field = $meta->fetch_field() ) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $this->refValues($parameters));
while ( $stmt->fetch() ) {
$x = array();
foreach( $row as $key => $val ) {
$x[$key] = $val;
}
$results[] = $x;
}
$result = $results;
}
$stmt->close();
$mysqli->close();
return $result;
}
?>
Check $mysqli->insert_id after executing insert query.