Convert raw sql to ZF2 statement - mysql

In zf2, how can i write following mysql query and execute it. ??
SELECT * FROM `user_modules` um JOIN ((SELECT vm.id, vm.module_code, vm.module_title,'video' AS type FROM video_master vm WHERE vm.is_deleted = 0) UNION (SELECT sm.id, sm.module_code, sm.module_title, 'slideshow' AS type FROM slideshow_master sm WHERE sm.is_deleted = 0) result ON um.module_id = result.id
WHERE um.user_id='3'

I found solution!!
$userId = '1';
$select = "SELECT * FROM `user_modules` um JOIN ((SELECT vm.id, vm.module_code, vm.module_title, 'video' AS type FROM video_master vm WHERE vm.is_deleted = 0) UNION (SELECT sm.id, sm.module_code, sm.module_title, 'slideshow' AS type FROM slideshow_master sm WHERE sm.is_deleted = 0)) temptable on um.module_id = temptable.id where um.user_id='". $userId ."'";
$resultSet = $this->adapter->query($select);
return $data = $this->resultSetPrototype->initialize($resultSet->execute())->toArray();
OR else can use ZF2 method:
$sql = new Sql($this->getAdapter());
$select = $sql->select()->from(array('um' => $this->table));
Get all slideshow modules
$select1 = $sql->select(array())->from(
array("slideshow" =>'slideshow_master'))
->columns(array('id','module_code','module_title',"type" => new Expression("'Slideshow'")));
$select1 = $sql->select(array())->from(
array("slideshow" =>'slideshow_master'))
->columns(array('id','module_code','module_title',"type" => new Expression("'Slideshow'")));
$select1->where("slideshow.is_deleted = 0");
$select1->order("slideshow.id");
Get all video modules
$select2 = $sql->select(array())->from(
array("video" => 'video_master'))
->columns(
array('id','module_code','module_title',"type" => new Expression("'Video'")));
$select2->where("video.is_deleted = 0");
$select2->order("video.id");
union of two first selects
$select1->combine ( $select2, 'UNION' );
$select->join(array('result' => $select1), "result.id = um.module_id");
$select ->where("um.user_id='". $userId. "'");
$statement = $sql->prepareStatementForSqlObject($select);
return $this->resultSetPrototype->initialize($statement->execute())->toArray();
Sorry for my typing and formatting.

Related

query with parentheses in zend framework 2.2

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

mySql statement

I have a sql statement where I want to get all the entry with the category of "Game" but do not want to retrieve the record with the code of "A00001".
Below is my sql code but there is an error in the where clause.
$sql1 = "SELECT * FROM productItem WHERE productName = '$name' AND skuCode != '$mySKU';";
$mySKU = 'A00001';
$sql1 = "SELECT * FROM productItem WHERE productName = '$name' AND skuCode != '$mySKU'";
You have an extra ; lurking somewhere in there. Be sure to sanitize $mySKU if it is user input and use prepared statements.
update: Using PDO:
$stmt = $dbh->prepare("SELECT * FROM productItem WHERE productName = :name AND skuCode != :mySKU");
if ($stmt->execute(array('name' => $name, "mySKU" => $mySKU))) {
$rows = $stmt->fetchAll(); //if you are sure there are records
Try this:
"SELECT * FROM productItem WHERE productName = '$name' AND skuCode <> '$mySKU';";
Not equal statement is <>
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_not-equal

ZF2 sanitize variables for DB queries

In making database queries in Zend Framework 2, how should I be sanitizing user submitted values? For example, $id in the following SQL
$this->tableGateway->adapter->query(
"UPDATE comments SET spam_votes = spam_votes + 1 WHERE comment_id = '$id'",
\Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE
);
You can pass parameters when you execute..
$statement = $this->getAdapter()->query("Select * from test WHERE id = ?");
$result = $statement->execute(array(99));
$resultSet = new ResultSet;
$resultSet->initialize($result);
You can also pass them directly to the query method
$statement = $this->getAdapter()->query(
"Select * from test WHERE id = ?",
array(99)
);
$result = $statement->execute();
$resultSet = new ResultSet;
$resultSet->initialize($result);
Both will produce the query "Select * from test WHERE id = '99'"
If you want to use named parameters:
$statement = $this->getAdapter()->query("Select * from test WHERE id = :id");
$result = $statement->execute(array(
':id' => 99
));
$resultSet = new ResultSet;
$resultSet->initialize($result);
If you want to quote your table/field names etc:
$tablename = $adapter->platform->quoteIdentifier('tablename');
$statement = $this->getAdapter()->query("Select * from {$tablename} WHERE id = :id");
$result = $statement->execute(array(
':id' => 99
));

Codeigniter query

My Query :
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where("`pos_item_sales`.`transaction_id` = '$transaction_id' AND (`pos_item_sales`.`item_barcode` = '$term' OR `pos_batch_infos`.`item_mbarcode` = '$term' OR `pos_item_infos`.`item_id` = '$term')");
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();
its solve my prob but i need like this query :
$term = $this->input->get('term',TRUE);
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where('pos_item_sales.transaction_id',$transaction_id);
$this->db->where('pos_item_sales.item_barcode',$term);
$this->db->or_where('pos_batch_infos.item_mbarcode',$term);
$this->db->or_where('pos_item_infos.item_id',$term);
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();
But I need a Query like :
SELECT *
FROM (`pos_item_infos`)
JOIN `pos_item_sales` ON `pos_item_sales`.`item_id` = `pos_item_infos`.`item_id`
JOIN `pos_batch_infos` ON `pos_batch_infos`.`item_id` = `pos_item_infos`.`item_id`
WHERE `pos_item_sales`.`transaction_id` = '11355822927'
AND (`pos_item_sales`.`item_barcode` = '8801962686156'
OR `pos_batch_infos`.`item_mbarcode` = '8801962686156'
OR `pos_item_infos`.`item_id` = '8801962686156')
how i solve this prob pls help because its not include ( ) in my or condition.
if you go through the codeigniter userguide.. you can see that there are 4 ways to call where clause...
All of these does the same things... and your first code is codeigniter style (if incase you are worried that is not) that is the 4th method by codeigniter userguide where you can write your own clauses manually... there is no difference in calling the where function in anyways...
so i would go with your first query
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where("`pos_item_sales`.`transaction_id` = '$transaction_id' AND (`pos_item_sales`.`item_barcode` = '$term' OR `pos_batch_infos`.`item_mbarcode` = '$term' OR `pos_item_infos`.`item_id` = '$term')");
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();
which is perfectly fine...
In cases of complex queries i find it easier to just send raw query like this :
$query = "your query";
$result = $this->db->query($query);
Don't forget to escape variables before inserting them to the query like this :
$var = $this->db->escape($var);
$query="SELECT *
FROM pos_item_infos
JOIN pos_item_sales ON pos_item_sales.item_id = pos_item_infos.item_id
JOIN pos_batch_infos ON pos_batch_infos.item_id = pos_item_infos.item_id
WHERE pos_item_sales.transaction_id = ?
AND (pos_item_sales.item_barcode = ?
OR pos_batch_infos.item_mbarcode = ?
OR pos_item_infos.item_id = ?)";
$params=array();
$params[]='11355822927';
$params[]='8801962686156';
$params[]='8801962686156';
$params[]='8801962686156';
$result=$this->db->query($query,$params);
$result=$result->result_array();
print_r($result);
Also, simplify your syntax with USING.
SELECT *
FROM pos_item_infos
JOIN pos_item_sales USING (item_id)
JOIN pos_batch_infos USING (item_id)
WHERE pos_item_sales.transaction_id = ?
AND (pos_item_sales.item_barcode = ?
OR pos_batch_infos.item_mbarcode = ?
OR pos_item_infos.item_id = ?)

Simplify the Doctrine query

I am new to Doctrine ORM or any ORM
$em = Zend_Registry::getInstance ()->entitymanager;
$p = $em->createQuery ( "
SELECT u
FROM Teon_Model_User u
WHERE u.app_auth IN (:app_auth)" );
$p->setParameter ( 'app_auth', $app_auth );
$array = $p->getArrayResult();
$customer_id = $array[0]['customer_id'];
$p = $em->createQuery ( "
SELECT p
FROM Teon_Model_Purchase p
WHERE p.customer IN (:customer_id)" );
$p->setParameter ( 'customer_id', $customer_id );
$array = $p->getArrayResult();
$purchase_id = $array[0]['id'];
$p = $em->createQuery ( "
SELECT pm
FROM Teon_Model_PurchaseManual pm
WHERE pm.purchase_id IN (:purchase_id)" );
$p->setParameter ( 'purchase_id', $purchase_id );
$array = $p->getArrayResult();
$m_id = $array[0]['manual_id'];
Can you simplify this query, it looks so stupid, I am using Doctrine in zend framework
this query is to authenticate the user whether he has manual_id in his purchases by supplying a authentication code..
Here's the 2 simple way i could think of to do this:
<?php
$em = Zend_Registry::getInstance()->entitymanager;
// 1st way
$user = $em->getRepository('Teon_Model_User')->findOneByAppAuth($app_auth);
$user->getCustomerId();
// 2nd way
$user = $em->getRepository('Teon_Model_User')->findOneBy(array(
'app_auth' => $app_auth,
));
$user->getCustomerId();