Zend DB Union Error - mysql

I have two query:
$select1 = $this->select()
->from(array('o'=>'table1'), array('*', 'o.field2 AS shared'))
->where('field4= ?', $input);
$select2 = $this->select()
->from(array('i'=>'table2'), array('*', 'ch.field1 AS shared'))
->where('ch.field5= ?', $input);
Both query works successfully. However, it does not work with the following union function even with shared parameter name. How come?
//Merge both query
$selectboth = $this->select()
->union(array($select1, $select2))
->order('shared');
$obj = $this->dbo->fetchRow($selectboth);
I am suspecting my fetchRow is the one causing this error in fetching.

if you have number of column same in both sql so you can ran into this issue:
http://framework.zend.com/issues/browse/ZF-4338
for example:
$select_q1 = $db->select()->...;
$select_q2 = $db->select()->...;
$main_select = $db->select()->union( array( '('.$select_q1 .')', '('.$select_q2 .')' ) );

Related

SQL - SELECT with WHERE statement return false despite present field in table

I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";

Symfony 1.4 select query with selected columns is not working

I want to run following query in symfony doctrine.
SELECT p.id AS id FROM skiChaletPrice p WHERE ski_chalet_id = ? AND month = ?
I wrote my doctrine query as following.
$q = Doctrine_Query::create()
->select('p.id AS id')
->from('skiChaletPrice p')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from);
$result = $q->fetchOne();
if ($result->count() > 0) {
return $result->toArray();
} else {
return null;
}
But my result always include all columns in the table. What the issue? Please help me.
The issue is that fetchOne() will return a Doctrine object, which implicitly contains all the columns in the table. $result->toArray() is converting that doctrine object to an array, which is why you get all the columns.
If you only want a subset of column, don't hydrate an object, instead do something like this:
$q = Doctrine_Query::create()
->select('p.id AS id')
->from('skiChaletPrice p')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from);
$results = $q->execute(array(), Doctrine::HYDRATE_SCALAR);
See http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/data-hydrators.html
This is how I should do it:
$result = Doctrine_Query::create()
->select('id')
->from('skiChaletPrice')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from)
->limit(1)
->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
// result will be a single id or 0
return $result ?: 0;
// if you want array($id) or array() inseatd
// return (array) $result;

How to run raw SQL Query with Zend Framework 2

Is there a way to execute a SQL String as a query in Zend Framework 2?
I have a string like that:
$sql = "SELECT * FROM testTable WHERE myColumn = 5"
now I want to execute this string directly.
Just pass the sql string to your db adapter like this:
$resultSet = $adapter->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
And if you want to pass parameters:
$sql = "SELECT * FROM testTable WHERE myColumn = ?";
$resultSet = $adapter->query($sql, array(5));
EDIT: Please note that the query method does not always returns a resultset. When its a resultset producing query(SELECT) it returns a \Zend\Db\ResultSet\ResultSet otherwise(INSERT, UPDATE, DELETE, ...) it will return a \Zend\Db\Adapter\Driver\ResultInterface.
And when you leave the second Parameter empty you will get a \Zend\Db\Adapter\Driver\StatementInterface which you can execute.
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Adapter;
$dbAdapterConfig = array(
'driver' => 'Mysqli',
'database' => 'dbname',
'username' => 'dbusername',
'password' => 'dbuserpassword'
);
$dbAdapter = new Adapter($dbAdapterConfig);
$sql = new Sql($dbAdapter);
$select = $sql->select();
$select->from('testTable');
$select->where(array('myColumn' => 5));
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
S. docu: Zend\Db → Zend\Db\Sql
If you are using tableGateway, you can run your raw SQL query using this statement,
$this->tableGateway->getAdapter()->driver->getConnection()->execute($sql);
where $sql pertains to your raw query. This can be useful for queries that do not have native ZF2 counterpart like TRUNCATE / INSERT SELECT statements.
If you have EntityManager $em on your hands, you can do something like this:
$select = $em->getConnection()->executeQuery("
SELECT a.id, a.title, a.announcement, asvc.service_id, COUNT(*) AS cnt,
GROUP_CONCAT(asvc.service_id SEPARATOR \", \") AS svc_ids
FROM article AS a
JOIN articles_services AS asvc ON asvc.article_id = a.id
WHERE
asvc.service_id IN (
SELECT tsvc.service_id
FROM tender AS t
JOIN tenders_services AS tsvc ON tsvc.tender_id = t.id
WHERE t.id = :tenderId
)
GROUP BY a.id
ORDER BY cnt DESC, a.id DESC
LIMIT :articlesCount
", [
'articlesCount' => 5,
'tenderId' => $tenderId,
], [
'articlesCount' => \PDO::PARAM_INT,
]);
$result = $select->fetchAll(); // <-- here are array of wanted rows
I think this way to execute complex queries is best for Zend. But may be I'm not very smart in Zend still. Will glad to see if it helps to someone.

Zend db update value not being set

I'm not sure what's missing with this update call, here's my code:
$table = new Application_Model_DbTable_ProductContaminant();
$db = $table->getAdapter();
$db->getProfiler()->setEnabled(true);
$data = array('value' => '999');
$where[] = $db->quoteInto('product_id = ?', $q['product_id']);
$where[] = $db->quoteInto('contaminant_id = ?', $k);
$table->update($data, $where);
print $db->getProfiler()->getLastQueryProfile()->getQuery();
And the profiler output is:
UPDATE `product_contaminants` SET `value` = ? WHERE (product_id = '4802') AND (contaminant_id = 69)
Why isn't 'value' being populated??
Value isn't populated because getQuery will only return a prepared statement with parameter placeholders. If you want the parameters used when it updates try this:
$db->getProfiler()->getLastQueryProfile()->getQueryParams()
More info here.

Update with Zend_DB on multiple rows

I am using Zend Framework. I have tree tables. Users and Groups and one table linking them.
I want to increment a field from users of a given group. To increment one User I do:
$table = 'users';
$update = array(
'ACLVersion' => new Zend_Db_Expr('ACLVersion + 1')
);
$where[] = $db->quoteInto('id = ?', $user);
$db->update($table, $update, $where);
I tried to use multiple wheres.
I have no clue how to join the tables in a where with Zend.
To use a JOIN with Zend_Db_Table, you have to disable the integrity check.
See example #27 in the ZF Reference Guide for Zend_Db_Table:
$table = new Bugs();
// retrieve with from part set, important when joining
$select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false)
->where('bug_status = ?', 'NEW')
->join('accounts', 'accounts.account_name = bugs.reported_by')
->where('accounts.account_name = ?', 'Bob');
$rows = $table->fetchAll($select);
Note that disabling the integrity check will also disable some of the automagic of the resulting recordset:
The resulting row or rowset will be
returned as a 'locked' row (meaning
the save(), delete() and any
field-setting methods will throw an
exception).
Load $num with a array of id's from a given group
The following code will do the job
$table = 'users';
$update = array(
'ACLVersion' => new Zend_Db_Expr('ACLVersion + 1')
);
$where = $db->quoteInto('id IN (?)', $num);
$db->update($table, $update, $where);