Reputation: 247
I've spent 2 hours for just a select statement.
What am I doing wrong?
public function fetchSpecific($moderatorid = 1)
{
$resultSet = $this->getDbTable()->fetchAll("moderatorid = ".$moderatorid);
$entries = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Network();
$entry->setId($row->id)
->setName($row->name)
->setModeratorId($row->moderatorid);
$entries[] = $entry;
}
return $entries;
}
It is all about this line:
$resultSet = $this->getDbTable()->fetchAll("moderatorid = ".$moderatorid);
It give me an error likes this:
Message: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
Upvotes: 0
Views: 935
Reputation: 69957
Technically that syntax should work, although I would recommend changing it up a bit in order to make sure that your data is properly escaped. What value do you see for $moderatorid
when you get that error? I suspect that variable is generating a syntax error for some reason.
Try this instead:
$results = $this->getDbTable()
->fetchAll($this->getDbTable()
->getAdapter()
->quoteInto('moderatorid = ?', $moderatorid));
This will make sure that $moderatorid
gets properly escaped and should help prevent syntax errors, and even more importantly it prevents possible SQL injections.
The other issue with using Zend_Db_Table::fetchAll()
is that when you encounter errors like this, it is difficult to debug the query being executed.
To get around this, construct the SELECT
statement yourself so you can echo the value if you need to debug the actual SQL being executed.
$select =
$this->getDbTable()
->select()
->from($this->getDbTable()) // optionally you can specify cols as the 2nd param
->where('moderatorid = ?', $moderatorid);
echo $select; // e.g. SELECT `table`.* FROM `table` WHERE (moderatorid = 1)
$results = $this->getDbTable()->fetchAll($select);
Hope that helps you solve your problem.
Some helpful references:
Zend_Db_Select
Zend_Db_Table
Upvotes: 2