query with parentheses in zend framework 2.2 - mysql

I want my query like this:
SELECT tbl_bids. * , tbl_department.vDeptName, tbl_user.vFirst
FROM tbl_bids
LEFT JOIN tbl_bids_department ON tbl_bids_department.iBidID = tbl_bids.iBidID
LEFT JOIN tbl_department ON tbl_department.iDepartmentID = tbl_bids_department.iDepartmentID
LEFT JOIN tbl_user ON tbl_user.iUserID = tbl_bids.iUserID
WHERE tbl_user.iUserID = '1' // with parantheses in where clause
AND (
tbl_department.vDeptName = 'PHP'
OR tbl_department.vDeptName = 'android'
)
GROUP BY tbl_bids.iBidID
ORDER BY iBidID DESC
LIMIT 0 , 30
But i can't find the way to get parantheses in my query,there are mutiple condition and loop will be there to make where clause..
here is my code
$select = $this->tableGateway->getSql()->select();
$select->columns(array('*'))
->join('tbl_bids_department', 'tbl_bids_department.iBidID = tbl_bids.iBidID', array(),"LEFT")
->join('tbl_department', 'tbl_department.iDepartmentID = tbl_bids_department.iDepartmentID',array(tbl_department.vDeptName),"LEFT")
->join('tbl_user', 'tbl_user.iUserID = tbl_bids.iUserID',array(tbl_user),"LEFT")
->group('tbl_bids.iBidID');
$where = new \Zend\Db\Sql\Where();
$where->equalTo( 'tbl_bids.eDeleted', '0' );
$sWhere = new \Zend\Db\Sql\Where();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if (isset($data['sSearch_'.$i]) && $data['sSearch_'.$i] != "")
{
if($aColumns[$i] == 'vDeptName'){
$allDept = explode(',', $data['sSearch_'.$i]);
foreach ($allDept as $key => $value) {
if($key == 0)
$sWhere->AND->equalTo("tbl_department.vDeptName", $value);
else
$sWhere->OR->equalTo("tbl_department.vDeptName", $value);
}
}elseif($aColumns[$i] == 'vFirst')
$sWhere->AND->equalTo("tbl_user.iUserID",$data['sSearch_'.$i]);
else
$sWhere->AND->like("tbl_bids.".$aColumns[$i], "%" . $data['sSearch_'.$i] . "%");
$select->where($sWhere); // here my where clause is create
}
}
//var_dump($select->getSqlString());
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
I have others many fields to pass through where which also have same problem of paratheses
if there is no any condition i can use nest() and unnest() predicate , but it will show me that string is not nested error,
So pls help me to find the solution.
Pls attach example with solution.

here is a short example
$where = new Sql\Where();
$where->equalTo('col',thirdVal')
->NEST //start braket
->equalTo('col','someVal')
->OR
->equalTo('col','secondVal')
->UNNEST //close bracet
hope this will help

Related

adding a condition to a WHERE clause based on a passed variable value mysql

I am a relative novice and could use some help with this problem.
This will be used in a search filter situation.
Users need to search by a value and 1 or more other values passed by the search form.
$name = $_POST['name'];
$sdate = $_POST['sdate'];
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$vehicle = $_POST['vehicle'];
$triptype = $_POST['triptype'];
If any of these values are '' I do not want them in the query, If they contain a value I do want them in the query.
SELECT * FROM form_data WHERE `resp_person` = '$name',
IF $sdate != '' then `sdate` = '$sdate',
IF $startdate != '' then `sdate` = *all values between $startdate and $enddate*,
IF $triptype != '' then `triptype` = '$vehicle',
IF $vehicle != '' then `vehicle` = '$vehicle', `sdate`
ORDER BY `sdate` DESC, `stime` DESC")
I know the code is wrong but it should give you a good idea of what I am trying to accomplish. Any guidance would be greatly appreciated.
A better way is to not use string concatenation to build the entire query, but rather use an sql library that supports prepared statements, such as PDO.
$pdo = new PDO('... connection string ...', username, password);
$where = '';
$possible_values = array('name', 'sdate', 'startdate', 'enddate', 'vehicle', 'triptype' );
$params = array();
foreach($possible_values as $val)
{
if(isset($_POST[$val]))
{
$params[] = $_POST[$val];
if($where == '')
{
$where = "WHERE $val = ?";
}
else
{
$where .= " AND $val = ?";
}
}
}
$stmt = $pdo->prepare("SELECT * FROM form_data " . $where);
$stmt->execute($params);
In cases like this, I prefer to build the query in pieces...
$wheres = array(); // Collect things to AND together
if ($searchterm != 'All') $wheres[] = "subject LIKE '%searchterm'";
if (...) $wheres[] = "...'";
...
if (count($wheres) > 0)
$where_str = "WHERE " . implode(' AND ', $wheres);
else
$where_str = '';
$order_str = (...) ? "ORDER BY ..." : '';
$limit_str = $limit ? "LIMIT $limit" : '';
$query = "SELECT ... FROM foo $where_str $order_str $limit_str";
Oh, and don't forget to use escape the strings on any data coming in from a form -- else a user can do nasty things to the SQL statement!

Doctrine with MySQL, Can I select all products within parent and sub categories?

I have done a bit off searching around for an answer, but most results are either not clear enough or I find it hard to implement in my current pattern... What I wish to achieve is having a query to select all products from the products table matching a category ID from the category table, But now i wish to also get products that are sub categories of the said parent category. I am using Doctrine 2 with codeigniter and my function so far looks like this
function searchForProducts( $offset, $limit ) {
$search = $this->input->get('search');
$category = (int)$this->input->get('category');
$supplier = (int)$this->input->get('supplier');
for( $i = 0; $i < 2; $i++ ) {
$select = ($i == 0) ? 'count(p)' : 'p';
$qb = $this->em->createQueryBuilder();
$qb ->select($select)
->from(self::ENTITY, 'p');
if( $i != 0) {
$qb ->setFirstResult( (int)$offset )
->setMaxResults( (int)$limit );
}
if( $search ) {
$qb ->where( "p.title LIKE :search" )
->orWhere( "p.sku LIKE :search" )
->setParameter('search', "%$search%");
}
if( $category ) {
$qb ->andWhere( "p.category = ?1" )
->setParameter(1, $category);
}
if( $supplier ) {
$qb ->andWhere( "p.supplier = ?2" )
->setParameter(2, $supplier);
}
if( $i == 0 ) {
$this->totalRows = $qb->getQuery()->getSingleScalarResult();
} else {
return $qb->getQuery()->getResult();
}
}
}
I also don't think it would be practical to get all products then do it from application level as I'm using pagination and products could become quite large.
When you do Product -> Category -> Child Categories -> Product then the resulting Products will not be returned in the same column. Thus Doctrine will hydrate them in the same manor. Which is no good if you want to use pagination on all the products.]
Your best bet is to use a native SQL with result set mapping. Then your query should use a UNION, so that the main Product lines up in the same columns as the child Products
To answer my own question, I decided to take the easy way out, and considering i would only have around 40 categories max, i don't think this should be much of a problem.
In my categories model class i created 2 static methods,
static function getCategoryWithChildren( $id = NULL ) {
$obj = new self;
$parent = $obj->getCategory( $id );
$list = array();
self::iterateCategoriesChildren($parent, $list);
return array_reverse($list);
}
static function iterateCategoriesChildren( $category, &$array ) {
if( $category->hasChildren() ) {
foreach( $category->getChildren() as $child ) {
self::iterateCategoriesChildren($child, $array);
}
}
$array[] = $category;
}
So pretty much this will get the parent and iterate all the children and assign each 1 to the flat array.
Then from my searchProducts method i just added a bit more under the $category check.
if( $category ) {
if( $this->settings->get('product_child_categories') ) {
$categories = Categories_model::getCategoryWithChildren($category);
foreach($categories as $_category) {
$qb ->orWhere( "p.category = " . $_category->getID() );
}
} else {
$qb ->andWhere( "p.category = ?1" )
->setParameter(1, $category);
}
}
May not be best or practical, but it works and does what I need for the time being.

can this phpbb query be optimized?

Here's some code adapted from phpBB. Near as I can tell it's trying to delete all topics wherein the only poster is the target user.
(note that for testing purposes I changed the final query from a DELETE to a SELECT)
<?php
$user_id = 66275;
mysql_connect('localhost', 'username', 'password');
mysql_select_db('db_name');
$start = microtime(true);
$total = 0;
define('POSTS_TABLE', 'phpbb_posts');
define('TOPICS_TABLE', 'phpbb_topics');
$sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
FROM ' . POSTS_TABLE . "
WHERE poster_id = $user_id
GROUP BY topic_id";
$result = mysql_query($sql);
$topic_id_ary = array();
while ($row = mysql_fetch_assoc($result))
{
$topic_id_ary[$row['topic_id']] = $row['total_posts'];
}
mysql_free_result($result);
if (sizeof($topic_id_ary))
{
$sql = 'SELECT topic_id, topic_replies, topic_replies_real
FROM ' . TOPICS_TABLE . '
WHERE ' . sql_in_set('topic_id', array_keys($topic_id_ary));
$result = mysql_query($sql);
$del_topic_ary = array();
while ($row = mysql_fetch_assoc($result))
{
if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']])
{
$del_topic_ary[] = $row['topic_id'];
}
}
mysql_free_result($result);
if (sizeof($del_topic_ary))
{
$sql = 'SELECT topic_id FROM ' . TOPICS_TABLE . '
WHERE ' . sql_in_set('topic_id', $del_topic_ary);
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
$total++;
echo $row[topic_id] . "\r\n";
}
}
}
function sql_in_set($field, $array, $negate = false, $allow_empty_set = false)
{
if (!sizeof($array))
{
if (!$allow_empty_set)
{
// Print the backtrace to help identifying the location of the problematic code
$this->sql_error('No values specified for SQL IN comparison');
}
else
{
// NOT IN () actually means everything so use a tautology
if ($negate)
{
return '1=1';
}
// IN () actually means nothing so use a contradiction
else
{
return '1=0';
}
}
}
if (!is_array($array))
{
$array = array($array);
}
if (sizeof($array) == 1)
{
#reset($array);
$var = current($array);
return $field . ($negate ? ' <> ' : ' = ') . $var;
}
else
{
return $field . ($negate ? ' NOT IN ' : ' IN ') . '(' . implode(', ', $array) . ')';
}
}
$elapsed = microtime(true) - $start;
echo "\r\ntook $elapsed seconds";
echo "\r\ngot $total rows back";
?>
This does three queries. First gets all the topics the target user has posted in and the number of times they've posted in each topic. The second gets how many replies each topic in the first query actually has. Then there's some PHP code to see which topics have had all their posts made by the target user. After that the code (prior to my changes) DELETEs all those topics.
Overall it seems to me that this could be written better by doing something like this:
SELECT t.topic_id
FROM phpbb_topics AS t
JOIN phpbb_posts AS p1
ON p1.topic_id = t.topic_id
AND p1.poster_id = $poster_id
LEFT JOIN phpbb_posts AS p2
ON p2.topic_id = t.topic_id
AND p2.poster_id <> $poster_id
WHERE p2.poster_id IS NULL;
Or maybe this:
SELECT t.topic_id
FROM phpbb_topics AS t
JOIN phpbb_posts AS p1
ON p1.topic_id = t.topic_id
AND p1.poster_id = $poster_id
AND t.topic_poster = $poster_id
AND t.topic_last_poster_id = $poster_id
LEFT JOIN phpbb_posts AS p2
ON p2.topic_id = t.topic_id
AND p2.poster_id <> $poster_id
WHERE p2.poster_id IS NULL
Testing this is actually quite difficult thanks to MySQLs caching but... from what testing I have been able to do it seems like the way phpBB is currently doing it is in fact faster. Which is surprising to me.
Any ideas?
It looks to me like you are on the right track. Try adding indexes to all the columns you are using in the joins as this can often drastically increase the speed of joins.

Yii CDbCriteria query matching mutiple rows in one table

I'm trying to figure out how to build a query using Yii's CDbCriteria that would be equivalent to the following:
SELECT
*
FROM
user u
JOIN (
SELECT *
FROM skill_assessment s
WHERE s.skill = 'HTML'
AND s.score >= 80
) b ON
(u.id = b.userId)
JOIN (
SELECT *
FROM skill_assessment s
WHERE s.skill = 'CSS3'
AND s.score >= 80
) c ON
(u.id = c.userId);
etc...
Here's what I have so far, that isn't working:
$criteria = new CDbCriteria();
$criteria->alias = "u";
$criteria->select = "*";
$criteria->join = "JOIN skill_assessment s ON (u.id=s.userId)";
for($i = 0; $i < count($skill_filters); $i++) {
$criteria->addCondition("s.skill='".$skill_filters[$i]->skill."' AND s.score >= ".$skill_filters[$i]->level);
}
$users = UserModel::model()->findAll($criteria);
Any help would be greatly appreciated.
Thanks in advance.
EDIT:
I was able to build out the sql query as a string and use findAllBySql, which returned the correct UserModels that matched my search criteria, the problem is that I haven't been able to get it to return the related SkillAssessmentModels. They don't come back either with the initial query, like this:
$users = UserModel::model()->with('skill_assessments')->findAllBySql($sql);
nor if I get the results like this:
$users = UserModel::model->findAllBySql($sql);
foreach($users as $user)
{
$user->skill_assessments = $user->getRelated('skill_assessments');
}
Any thoughts on how I can get those related models?
The strange thing is that elsewhere in my application, I CAN get the related models if I do this:
$user = UserModel::model->findByPk($id);
$user->skill_assessments->getRelated('skill_assessments');
Second param for addCondition is by default 'AND'. Is this what you are looking for? May be you should define 'OR' for $operator and add braces around condition.
But in your case addCondition will by applied to the user table, not to the JOIN.
I think that this should work for you:
$criteria = new CDbCriteria();
$criteria->alias = "u";
$criteria->together= "skill_assessment";
$where = array();
for($i = 0; $i < count($skill_filters); $i++) {
$where[] = "(s.skill='".$skill_filters[$i]->skill."' AND s.score >= ".$skill_filters[$i]->level . ')';
}
$criteria->join = 'JOIN skill_assessment s ON (u.id=s.userId' . ( $where ? ( ' AND (' . join( ' OR ', $where ) . ')' ) : '') . ')';
$users = UserModel::model()->findAll($criteria);
Fetch _skill_assessment_ like this:
foreach( $users->skill_assessment as $skill_assessment )
{
echo $skill_assessment->userId;
}
At this level keep it simple:
$sql="select * from mytable where id = :id";
$cmd = Yii::app()->db->createCommand($sql)->bindParam("id", $res_id);
$cmd->execute();
Thanks a lot to Boris Belenski!
What you suggested wasn't quite what I needed, but it did get me to what I needed. Here is what I ended up with that works:
$str = "abcdefghijklmnopqrstuvwxyz";
$idxs = str_split($str);
$criteria = new CDbCriteria();
$criteria->alias = "u";
$joins = array();
for($i = 0; $i < count($skill_filters); $i++)
{
$joins[] = " JOIN (SELECT * FROM skill_assessment s WHERE s.skill = '" . $skill_filters[$i]->skill ."' AND s.score >= " . $skill_filters[$i]->level . ") " . $idxs[$i] . " ON (u.id = " . $idxs[$i] . ".userId) ";
}
$criteria->join = join(' ', $joins);
$users = UserModel::model()->findAll($criteria);
foreach($users as $user)
{
$user->skill_assessments = $user->getRelated('skill_assessments');
}
The really key part is that $joins array.
This will allow you to get all the users that match ALL the criteria for row matches in the skill_assessments table.
Also, I could probably lazily load the skill assessments in the View in a normal view, but I need to get all the skill_assessments for each user now in order to pass them back in an ajax response with the user.

Zend DB and Conditional Case Statements

I have a zend app that displays a league table of race results. The basic process is to determine the list of events to be included, and then dynamically add a set of columns to a SQL query. My initial implementation is rather rubbish and i want to refector it. I manually build up a string of SQL and at the very end call db->fetch(). I know - crap code, but i was still learning zend and had a deadline.
public function league()
{
...
$SQL = 'SELECT rr.runner AS runnerid, ru.firstname as firstname, ru.surname as surname, ';
// get the list of events
foreach($events as $eventrow)
{
$eventTable = new Model_DbTable_Event();
$event = $eventTable->find($eventrow->event)->current();
// generate the conditional column
$sum = $this->getEventSQL($event,$division->gender);
// append to the SQL string (nasty)
$SQL = $SQL . $sum;
}
$SQL = $SQL . 'lrd.racesComplete, lrd.pointsTotal, c.name as company ';
$SQL = $SQL . 'FROM raceresult rr ';
$SQL = $SQL . 'JOIN runner ru ON rr.runner = ru.id ';
$SQL = $SQL . 'LEFT JOIN company c ON c.id = ru.company ';
$SQL = $SQL . 'JOIN race ra ON rr.race = ra.id ';
...
...
$db = Zend_Db_Table::getDefaultAdapter();
$this->view->leaguetable = $db->fetchAll($SQL);
}
// create the SUM sql statement for a specific event
// SUM(CASE rr.race WHEN 15 THEN rr.points ELSE NULL END) as Result1,
// SUM(CASE rr.race WHEN 16 THEN rr.points ELSE NULL END) as Result2,
function getEventSQL($event,$type)
{
$eventTable = new Model_DbTable_Event();
$sum_sql = 'SUM(CASE rr.race ';
foreach($races as $race)
{
$sum_sql = $sum_sql . sprintf('WHEN %d',$race->id) . ' THEN rr.points ';
}
$sum_sql = $sum_sql . sprintf('ELSE NULL END) as \'%s\',',$event->id);
return $sum_sql;
}
I know i need to use the SQL SELECT/CASE statements.
Conditional column for query based on other columns in MySQL
I want to move this logic to a class that extends Zend_Db_Table_Abstract but i'm still unsure what is the best way to conditionally control the columns that are selected. I know i can add multiple where() clauses, can the column() method be used in this scenario?
class Model_DbTable_League extends Zend_Db_Table_Abstract
{
protected $_name = 'leaguerunnerdata';
protected $_primary = 'Id';
public function leagueTable($min,$max)
{
$sql = $this->select()
->setIntegrityCheck(false)
->from(array('l'=>'league'),array('col','col2','col3'))
->where('l.league = ?',1)
->where('r.standard > ?',$min)
->where('r.standard < ?',$max)
->order('l.pointsTotal DESC');
return $this->fetchAll($sql);
}
....
Any ideas/suggestions?
The perfecto answerino
$select = $this->select()->setIntegrityCheck(false)
$select->from(array('l' => 'league'), array('leagueId'=> 'id', 'name','location','competitionName','eventManager','owner' ) )
->join(array('r' => 'whateverRTableIs'),
'r.id = l.id',
array())
->where('l.league = ?',1)
->where('r.standard > ?',$min)
->where('r.standard < ?',$max)
->order('l.pointsTotal DESC');
return $this->fetchAll($select);
I figured out that i could use the 'columns()' method to dynamically add extra fields to my query, and use the Zend_Db_Expr to correctly format the specific value for the column.
$select = $this->select()
->setIntegrityCheck(false)
->from(array('raceresult'=>'raceresult'),array())
->join(array('runner'=>'runner'),'runner.id=raceresult.runner',array('id','firstname','surname'));
foreach($races as $taggedrace)
{
$select->columns(new Zend_Db_Expr(
sprintf("SUM(CASE raceresult.race WHEN %d THEN raceresult.points ELSE NULL END) as %s",
$taggedrace->raceid,$taggedrace->tag)));
}
$select->join(array('race'=>'race'),'race.id = raceresult.race',array())
->join(array('event'=>'event'),'race.event = event.id',array())
->join(array('leagueevent'=>'leagueevent'),'leagueevent.event = event.id',array())
->join(array('leaguerunnerdata'=>'leaguerunnerdata'),
'leaguerunnerdata.runner = raceresult.runner AND leaguerunnerdata.league=leagueevent.league',
array('racesComplete','pointsTotal'))
->joinLeft(array('company'=>'company'), 'company.id = runner.company',array('name'))
->where( sprintf('leaguerunnerdata.standard BETWEEN %d AND %d ',$division->min,$division->max))
->where('runner.gender= ?',$division->gender)
->where('leagueevent.league = ?',$league)
->group(array('raceresult.runner','leaguerunnerdata.racesComplete','leaguerunnerdata.pointsTotal'))
->order(array('leaguerunnerdata.pointsTotal desc'));