zend framework 1.11.5 is choking on search function - mysql db - zend-framework

ZF 1.11.5 is puking all over this search function. i've tried creating the query several different ways, sent the sql statement to my view, copied and pasted the sql statement into phpMyAdmin and successfully retrieved records using the sql that ZF is choking on. i have been getting a coupld of different errors: 1) an odd SQL error about 'ordinality' (from my Googling ... it seems this is a ZF hang up .. maybe?) and 2) Fatal error: Call to undefined method Application_Model_DbTable_Blah::query() in /blah/blah/blah.php on line blah
public function searchAction($page=1)
{
$searchForm = new Application_Model_FormIndexSearch();
$this->view->searchForm = $searchForm;
$this->view->postValid = '<p>Enter keywords to search the course listings</p>';
$searchTerm = trim( $this->_request->getPost('keywords') );
$searchDb = new Application_Model_DbTable_Ceres();
$selectSql = "SELECT * FROM listings WHERE `s_coursedesc` LIKE '%".$searchTerm."%' || `s_title` LIKE '%".$searchTerm."%'";
$selectQuery = $searchDb->query($selectSql);
$searchResults = $selectQuery->fetchAll();
}
here's my model ....
class Application_Model_DbTable_Ceres extends Zend_Db_Table_Abstract
{
protected $_name = 'listings';
function getCourse( $courseId )
{
$courseid = (int)$courseId;
$row = $this->fetchRow('id=?',$courseId);
if (!$row)
throw new Exception('That course id was not found');
return $row->toArray();
}
}
never mind the view file ... that never throws an error. on a side note: i'm seriously considering kicking ZF to the curb and using CodeIgniter instead.
looking forward to reading your thoughts. thanks ( in advance ) for your responses

You're trying to all a method called query() on Zend_Db_Table but no such method exists. Since you have built the SQL already you might find it easier to call the query on the DB adapter directly, so:
$selectSql = "SELECT * FROM listings WHERE `s_coursedesc` LIKE '%".$searchTerm."%' || `s_title` LIKE '%".$searchTerm."%'";
$searchResults = $selectQuery->getAdapter()->fetchAll($selectSql);
but note that this will give you arrays of data in the result instead of objects which you might be expecting. You also need to escape $searchTerm here since you are getting that value directly from POST data.
Alternatively, you could form the query programatically, something like:
$searchTerm = '%'.$searchTerm.'%';
$select = $selectQuery->select();
$select->where('s_coursedesc LIKE ?', $searchTerm)
->orWhere('s_title LIKE ?', $searchTerm);
$searchResults = $searchQuery->fetchAll($select);

Related

Check if pg_prepare was already executed

Is there a way to check if pg_prepare already executed and remove it from the session?
Seems like pg_close doesn't remove prepared statement from the session. Kind of seems like a bug in php, but maybe I'm missing something or maybe there is a workaround.
public static function readSubdomains($dcName, $filter = null) {
// ...
$conn = pg_pconnect($connectionString);
// ...
$result = pg_prepare($conn, "subdomains", "SELECT subdomain
from tenants
where $where
order by 1 asc
");
$result = pg_execute($conn, "subdomains", $params);
// ...
pg_close($conn);
}
Second call to readSubdomains shows a warning like this:
Warning: pg_prepare(): Query failed: ERROR: prepared expression "subdomains" already exists in inc/TestHelper.php on line 121
Always check the official manuals for this sort of stuff.
https://www.postgresql.org/docs/current/view-pg-prepared-statements.html
Oh - if pg_close isn't dropping prepared statements then it isn't closing the connection. You might have some connection pooling involved.

zendframework 2 select max of a column

I'm using ZendFramework 2 and TableGateway which is fine for normal select statements. But I can't seem to find how to get a max of a column using ZendFramework 2 select.
My select should look something like
SELECT MAX( `publication_nr` ) AS maxPubNr FROM `publications`
and my code looks like:
use Zend\Db\TableGateway\TableGateway;
class PublicationsTable
{
protected $tableGateway;
...
public function getMaxPubicationNr()
{
$rowset = $this->tableGateway->select(array('maxPubNr' => new Expression('MAX(publication_nr)')));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not retrieve max Publication nr");
}
return $row;
}
If you look at the TableGateway you will notice the parameters for the Select method are actually passed to the Where part of the Query, which is making your query incorrect.
You need to modify the Select Object directly as the TableGateway won't give you any proxy methods to do this.
You could try something like this:
public function getMaxPubicationNr()
{
$select = $this->tableGateway->getSql()->select();
$select->columns(array(
'maxPubNr' => new Expression('MAX(publication_nr)')
));
// If you need to add any where caluses you would need to do it here
//$select->where(array());
$rowset = $this->tableGateway->selectWith($select);
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not retrieve max Publication nr");
}
return $row;
}
I've not tested it, but that should just about get you there :)
You will probably bump into another issue though, and that will be due to the TableGateway trying to build you an object from the result, but you aren't bringing back a full row to build an object, you're just bringing back a single Column.
I would just add use the Db/Select objects to do this and not bother with the GateWay to be honest, I don't think it's supposed to be used like this.

zf2 When I do addFeature(new Feature\SequenceFeature,...) for Postgres PDO, insert fails because columns and values are nulled out

I'm in Zend Framework 2, trying to get the last inserted id after inserting using postgresql PDO. The insert works fine unless I add a SequenceFeature, like this:
class LogTable extends AbstractTableGateway
{
protected $table = 'log';
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
$this->featureSet = new Feature\FeatureSet();
$this->featureSet->addFeature(new Feature\SequenceFeature('id','log_id_seq'));
$this->resultSetPrototype = new ResultSet();
$this->resultSetPrototype->setArrayObjectPrototype(new Log());
print_r($this->getFeatureSet());
$this->initialize();
}
When I later do an insert like this:
$this->insert($data);
It fails, because INSERT INTO "log" () VALUES (), so for some reason zf2 is nulling out the columns and values to insert, but only if I add that SequenceFeature.
If I don't add that feature, the insert works fine, but I can't get the last sequence value. Debugging the Zend/Db/Sql/Insert.php, I found that the values function is accessed twice with the SequenceFeature in there, but only once when it's not in there. For some reason when the SequenceFeature is there, all the insert columns and values are nulled out, possibly because of this double call? I haven't investigated further yet, but maybe it's updating the sequence and then losing the data when making the insert?
Is this a bug, or is there just something I'm missing?
Screw it! We'll do it live!
Definitely not the best solution, but this works. I just cut and pasted the appropriate code from Zend/Db/TableGateway/Feature/SequenceFeature.php and added it as a function to my LogTable class:
public function nextSequenceId()
{
$sql = "SELECT NEXTVAL('log_id_seq')";
$statement = $this->adapter->createStatement();
$statement->prepare($sql);
$result = $statement->execute();
$sequence = $result->getResource()->fetch(\PDO::FETCH_ASSOC);
return $sequence['nextval'];
}
Then I called it before my insert in my LogController class:
$data['id'] = $this->nextSequenceId();
$id = $this->insert($data);
Et voila! Hopefully someone else will explain to me how I'm really supposed to do it, but this will work just fine in the interim.

WHERE IN sql query using Zend_Db

Zend Framework beginner here. I'm trying to fetch all the Xbox titles of a video game database. One table contains games. Another table contains game types (ie. Xbox, Xbox Live Arcade, ...). I normally use the following query to get the Xbox titles.
How can I execute the same query using Zend_Db?
Thanks,
SELECT titleGame
FROM Game
WHERE idGameType IN (
SELECT idGameType
FROM GameType
WHERE nameGameType = 'Xbox')
That could be rewritten in Zend Framework a few ways. Here is the way I typically write selects like that using Zend_Db_Table_Select.
<?php
// For brevity, $dbTable = a Zend_Db_Table object
// first construct the subquery/join for the IN clause
// SELECT idGameType FROM GameType HERE nameGameType = 'Xbox'
$subselect = $dbTable->select()
->from('GameType', array('idGameType'))
->where('nameGameType = ?', 'Xbox'); // quotes Xbox appropriately, prevents SQL injection and errors
// construct the primary select
// SELECT titleGame FROM Game WHERE idGameType IN (subquery)
$select = $dbTable->select()
->setIntegrityCheck(false) // allows us to select from another table
->from($dbTable, array('titleGame'))
->where('idGameType IN (?)', $subselect);
$results = $select->query()->fetchAll(); // will throw an exception if the query fails
if(0 === count($results)) {
echo "No Results";
}else{
foreach($results as $result){
echo $result['titleGame'] . '<br />';
}
}
You can also write the SQL as a string, but when possible, the object-oriented approach is ideal because it makes the queries more portable, and most importantly makes it very easy to secure your queries.
Example:
$db = Zend_Db_Table::getDefaultAdapter(); // get the default Db connection
$db->select("select * from table where id = 3"); // doable, but not recommended
You can also create a prepared statement through Zend_Db_Statement to PHP's PDO extension.
$sql = 'SELECT * FROM bugs WHERE reported_by = ? AND bug_status = ?';
$stmt = new Zend_Db_Statement_Mysqli($db, $sql);
$stmt->execute(array('goofy', 'FIXED'));
The first approach, the object oriented fluent interface is what you will see the most, and the method I would recommend starting out with and using.
Read through the Zend_Db Manual Pages, and in particular, Zend_Db_Table_Select, Zend_Db_Table, and Zend_Db_Adapter for more information. Even a quick read through over the ZF Quickstart paying specific attention to the Db portion is helpful. It will show how to set up table classes to be a gateway between your application and the database.
SELECT titleGame FROM Game
LEFT JOIN GameType ON GameType.idGameType = Game.idGameType
WHERE GameType.nameGameType = 'Xbox'
Why not use a join instead? From my experience a subselect inside of IN is very slow in MySQL.
$select = $db->select();
$select->from('Game', array('titleGame'));
$select->joinLeft('GameType', 'GameType.idGameType = Game.idGameType', array());
$select->where("GameType.nameGameType = 'Xbox'");

It is possible to execute MySQLi prepared statement before the other one is closed?

Lets say I have a prepared statement. The query that it prepares doesn't matter. I fetch the result like above (I can't show actual code, as it is something I don't want to show off. Please concentrate on the problem, not the examples meaningless) and I get
Fatal error: Call to a member function bind_param() on a non-object in... error. The error caused in the called object.
<?php
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
class table2Info{
private $mysqli;
public function __construct($_mysqli){
$this->mysqli = $_mysqli;
}
public function getInfo($id)
{
$db = $this->mysqli->prepare('SELECT info FROM table2 WHERE id = ? LIMIT 1');
$db->bind_param('i',$db_id);
$db_id = $id;
$db->bind_result($info);
$db->execute();
$db->fetch();
$db->close();
return $info;
}
}
$t2I = new table2Info($mysqli);
$stmt->prepare('SELECT id FROM table1 WHERE name = ?');
$stmt->bind_param('s',$name);
$name = $_GET['name'];
$stmt->bind_result($id);
$stmt->execute();
while($stmt->fetch())
{
//This will cause the fatal-error
echo $t2I->getInfo($id);
}
$stmt->close();
?>
The question is: is there a way to do another prepared statement while another one is still open? It would simplify the code for me. I can't solve this with SQL JOIN or something like that, it must be this way. Now I collect the fetched data in an array and loop through it after $stmt->close(); but that just isn't good solution. Why should I do two loops when one is better?
From the error you're getting it appears that your statement preparation failed. mysqli::prepare returns a MySQLi_STMT object or false on failure.
Check for the return value from your statement preparation that is causing the error. If it is false you can see more details by looking at mysqli::error.