Zend Tutorial: Difficult to find row 1 - zend-framework

I am trying to follow the tutorial https://framework.zend.com/manual/2.4/en/user-guide/database-and-models.html
I have the problem, that i can't use the getAlbum(1) function.
It is possible to fetchAll() -> All rows returned
If I want to use getAlbum($personalnummer) -> Could not find row 1
Yes, there is an entry with Personalnummer 1 in the database and it is type int. The only difference is that, I use a Microsoft SQL Server, but the Configuration is right because all rows could be returned.
Any ideas?
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getAlbum($personalnummer)
{
$personalnummer = (int) $personalnummer;
$rowset = $this->tableGateway->select(array('Personalnummer' => $personalnummer));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $personalnummer");
}
return $row;
}

try this if it helps replace
$rowset = $this->tableGateway->select(array('Personalnummer' => $personalnummer));
with this
$where = new \Zend\Db\Sql\Where();
$where->equalTo('Personalnummer', $personalnummer);
$rowset = $this->tableGateway->select($where)

Related

Understanding issue get one row from database with 2 parameters

I thought it would work find, but it doesn't.
I have a method in my modelclass like this:
public function getUnitbyName2($unitname, $ProjectID)
{
//$id = (int) $id;
$rowset = $this->tableGateway->select(['Unitname' => $unitname], ['ProjectID' => $ProjectID]);
$row = $rowset->current();
if (! $row) {
// throw new RuntimeException(sprintf(
// 'Could not find row with identifier %d',
// $unitname
// ));
$row=0;
}
return $row;
}
If I give an existing unitname and a non existent project_ID I expect to get some 0 value. But I always get the number of the unit in the first project with the given unitname. It is common that the unitname exists in several different projects.
The function is supposed to get the right record if exist using both parameters.
My question is, what's wrong with using 2 parameters connected by AND?
AbstractTableGateway::select() accepts one argument, you are passing 2:
You need to pass 1, combine the 2 arrays.
Change your code to:
$rowset = $this->tableGateway->select(['Unitname' => $unitname, 'ProjectID' => $ProjectID]);
Zend table Gateways

Call to undefined method Application_Model_DbTable_Projects::lastInsertId()

I want to retrieve the id of the last inserted row. This is the code I use in the mapper:
public function save(Application_Model_Projects $project)
{
$data = array(
'id_user' => $project->getIdUser(),
'project_name' => $project->getProjectName(),
'project_description' => $project->getProjectDescription(),
'due_date' => $project->getDueDate(),
'id_customer' => $project->getIdCustomer()
);
if(($id = $project->getId()) === null) {
unset($data['id']);
$this->getDbTable()->insert($data);
return $this->getDbTable()->lastInsertId();
}else {
$this->getDbTable()->update($data, array('id = ?', (int) $id));
return $id;
}
}
According to the code above, it should return the id of the object. It is either the id after insertion or the current id.
The code where I use this function:
$currentUser = new Application_Model_UserAuth();
$project = new Application_Model_Projects();
$project->setProjectName($formValues['projectName'])
->setProjectDescription($formValues['projectDescription'])
->setDueDate(date("Y-m-d",strtotime($formValues['dueDate'])))
->setIdCustomer($formValues['assignCustomer'])
->setIdUser($currentUser->id);
$projectMapper = new Application_Model_ProjectsMapper();
$idProject = $projectMapper->save($project);
The error I get is:
Fatal error: Call to undefined method Application_Model_DbTable_Projects::lastInsertId()
What is wrong with this? Shouldn't that return the last id? Because it is triggered upon insertion. In another sequence of code I call the lastInsertId: $Zend_Db_Table::getDefaultAdapter()->lastInsertId(). The only difference is that now I call lastInsertIt on a dbTable, that extends Zend_Db_Table_Abstract.
The answer to my question above is that I should call getAdapter() before lastInsertId().
Updated code:
if(($id = $project->getId()) === null) {
unset($data['id']);
$this->getDbTable()->insert($data);
return $this->getDbTable()->getAdapter()->lastInsertId();
}
If it is an single-column Primary Key the return value is lastInsertId by default, so you also can use this:
return $this->getDbTable()->insert($data);

Is this a valid way to check if db_row exists?

I am working with Zend and I needed to check whether a row in the DB already exists (A simple solution to get rid of the duplicate key error I was getting). I tried several things but nothing seemed to work... (for example the Zend_Validate_Db_NoRecordExists method)
So I wrote the following the code and I was wondering if this is a valid way to do it, or if I should do things differently:
In the model:
$where = $condition = array(
'user_id = ' . $user_id,
'page_id = ' . $page_id
);
$check = $this->fetchRow($where);
if(count($check) > 0) {
return null;
}else{
// Here I create a new row, fill it with data, save and return it.
}
And then in my view:
if($this->result != null) { /* do stuff */ }else{ /* do other stuff */ }
It does work but it does seem to take more time (duh, because of the extra query) and I am a bit unsure whether I should stick with this..
Any recommendation is welcome :)
Assuming you have coded your function in your controller
$row = $this->fetchRow($where); //If no row is found then $row is null .
if(!$row)
{
$row = $dbTb->createNew($insert); //$insert an associative array where it keys map cols of table
$row->save();
$this->view->row_not_found = true;
}
return $row;
In your view you can do this
if($this->row_not_found)
{
}else {
}

Zend Db query to select all IDs

How would I write an Zend DB query to select all from the column ID?
So far I have tried:
public function getLatestUserID()
{
$ids = $this->select()
->where('id = ?');
return $ids;
}
But to no avail.
You just want the id column,
You failed to call an execute command.
try:
//assuming you are using a DbTable model
public function getLatestUserID()
{
$ids = $this->fetchAll('id');
return $ids;
}
I would do it like this, because I use the select() object for everything:
public function getLatestUserID()
{
$select = $this->select();
//I'm not sure if $this will work in this contex but you can out the table name
$select->from(array($this), array('id'));
$ids = $this->fetchAll($select);
return $ids;
}
The first two examples should return just the id column of the table, now if you actually want to query for a specific id:
public function getLatestUserID($id)
{
$select = $this->select();
$select->where('id = ?', $id);
//fetchAll() would still work here if we wanted multiple rows returned
//but fetchRow() for one row and fetchRowset() for multiple rows are probably
//more specific for this purpose.
$ids = $this->fetchRow($select);
return $ids;
}
make sure your class containing getLatestUserID does extend Zend_Db_Table_Abstract also :
$ids = $this->select()->where('id = ?'); can't work because where('id = ?'); expects an id value like where('id = ?', $id);
if what you want is the latest inserted row's Id use :
$lastInsertId = $this->getAdapter()->lastInsertId();
(however if you are using an oracle database this will not work and you should use $lastInsertId = $this->getAdapter()->lastSequenceId('USER_TABLE_SEQUENCE'); )

Zend Framework, echo message if (!$row) not working

This should be straight forward if the row count is 0 I want to echo a message. Here is what I have:
public function getClubComment($id) {
$id = (int) $id;
$row = $this->fetchRow('club_id = ' . $id);
if (!$row) {
echo 'No comments';
}
return $row->toArray();
var_dump($row);
}
maybe try something like:
//not sure if this will work as I don't do this kind of request anymore
public function getClubComment($id) {
$id = (int) $id;
$row = $this->fetchRow('club_id = ?', $id);
if (!$row) {echo 'No comments';}
return $row->toArray();
var_dump($row);
}
I think you'll be happier doing something like this, takes most of the guess work out.
public function getClubComment($id) {
$id = (int) $id;
//create instance of Zend_Db_Select object
$select = $this select();
$select->where('club_id = ?', $id);
//fetchRow using Zend_Db_Select object
$row = $this->fetchRow($select);
//fetchRow() returns NULL so may as well test for that.
if ($row === NULL) {
throw new Zend_Db_Table_Exception();
}
return $row->toArray();
var_dump($row);
}
Zend_Db_Select is really useful to use in the models as it normally takes care of properly quoting values and it very easy to build a fairly complex sql query with any sql. In this example I used discrete lines for each part of the select() but I could as easily have strung them all together. I personally like each line separate so I can change or troubleshoot easily.
fetchRow returns an object, even if there is no results, that is why the condition in the if statement is always false, try this
if (!count($row))