Zend Framework Inner Join Query - frameworks

I am not sure why Zend makes it difficult to write queries. I am from CodeIgniter background.
I want to write this query
SELECT tbllicenses.*, tblclients.email As clientemail FROM tbllicenses
INNER JOIN tblclients ON tblclients.id = tbllicenses.clientid
Do you know how can I write this query without using "table AS t" kind of assignments ?

Having table aliases is the standard way to write queries. so if you will go for zend join functions then aliases are required. Another way around is that you can pass the whole query to '$this->db->query("query....")'.

One way to do it could be:
class Application_Model_Soa_Service_LicenseService extends Zend_Db_Table_Abstract
{
public function getLicenses()
{
$statementString = " ";
$statementString .= " SELECT ";
$statementString .= " tbllicenses.*, ";
$statementString .= " tblclients.email As clientemail ";
$statementString .= " FROM tbllicenses ";
$statementString .= " INNER JOIN tblclients ON tblclients.id = tbllicenses.clientid ";
$statementQuery = $this->_db->prepare($statementString);
$statementQuery->execute();
$rowsetData = $statementQuery->fetchAll();
return $rowsetData;
}
}

Related

How to get all table names from db and paginate them

Trying to paginate DB::select('SHOW TABLES')->paginate(1); but got error Call to a member function paginate() on array. How can I get all the tables and paginate them?
Since you can use \DB:select for your query, it will response the array instead of the collection. So, you can't make the pagination from it.
You can use LengthAwarePaginator for this case, please see the following code:
$sql .= 'SHOW TABLES LIMIT ' . $offset . ', ' . $limit;
$result = \DB::select(\DB::raw($sql));
$myPaginator = new \Illuminate\Pagination\LengthAwarePaginator($result, $data['count'], $limit, $page, ['path' => action('MyController#index')]);
$data['result'] = $result;

Translation in extension fails when not logged into backend

I have an extbase extension that translates some variables on pages using this
if (is_array($row) && $row['sys_language_uid'] != $GLOBALS['TSFE']->sys_language_content && $GLOBALS['TSFE']->sys_language_contentOL) {
$row = $GLOBALS['TSFE']->sys_page->getRecordOverlay($table, $row,$GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
}
But there's a strange bug. It only works, when I'm logged into the backend. As soon as I log out, I can only see the default language.
Using Typo3 8.7
Any ideas what this could cause?
This can happen if you have config.sys_language_overlay = 0 defined globaly on your page object within your Typoscript Setup.
There is a ticket entry in the Typo3 Forge that goes a bit deeper as to why this happens and provides some workarrounds if you need those.
So, I didn't figure out what the problem was, but found my own workaround for the problem. Here's the updated Code:
$table = 'tx_myExt';
$query = "SELECT * FROM ".$table." WHERE pid=".$pid;
$query .= ' AND (sys_language_uid IN (-1,0) OR (sys_language_uid = ' .$GLOBALS['TSFE']->sys_language_uid. ' AND l10n_parent = 0))';
$query .= " AND deleted=0 AND hidden=0";
$res = $GLOBALS['TYPO3_DB']->sql_query($query);
while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
//localization
// check for language overlay if:
// * row is valid
// * row language is different from currently needed language
// * sys_language_contentOL is set
if (is_array($row) && $row['sys_language_uid'] != $GLOBALS['TSFE']->sys_language_content && $GLOBALS['TSFE']->sys_language_contentOL) {
$query2 = "SELECT * FROM ".$table." WHERE pid=".$pid;
$query2 .= ' AND sys_language_uid = ' .$GLOBALS['TSFE']->sys_language_content;
$query2 .= ' AND l10n_parent = ' . $row['uid'];
$query2 .= " AND deleted=0 AND hidden=0";
$res2 = $GLOBALS['TYPO3_DB']->sql_query($query2);
$row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res2);
//$row = $GLOBALS['TSFE']->sys_page->getRecordOverlay($table, $row,$GLOBALS['TSFE']->sys_language_content, $GLOBALS['TSFE']->sys_language_contentOL);
}
}
So, instead of using getRecordOverlay I'm just repeating the query, accessing the translated record directly. I did read somewhere that this is bad practice, but hey, it works for now, that's all that matters ;)
Still, if someone finds a solution to the original problem, I'd be happy to see that.

Passing variables into sqlplus query in perl

I'm having an issue here. I am trying to pass a variable into a sqlplus query, and it does not seem to be working.
my $connect = DBI->connect('DBI:Oracle:',$dbuser,$dbpasswd);
my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle='?'", $cycle;
my $query_handle = $connect->prepare($query);
$query_handle->execute();
$cmte_money = $query_handle->fetchrow_array();
print 'Money: ';
print $cmte_money;
if($cmte_money > 0)
{
print 'HI';
}
else
{
print 'NOOOO';
}
I can get the query to work when I change the "cycles" variable from a variable to a constant, and the if statement checking will print hi, so the databases work I'm positive.
I've scoured the internet, and I can't seem to find an answer.
First, you mean to use a placeholder but you don't.
where cycle='?' -- This is a string
should be
where cycle=? -- This is a placeholder
And then there's problem that you don't actually pass a value for the placeholder.
$query_handle->execute();
should be
$query_handle->execute($cycle);
The replacements for placeholders get passed to execute, so:
my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle=?";
my $query_handle = $connect->prepare($query);
$query_handle->execute($cycle);
The code you had would have triggered warnings if you had them enabled; make sure you do and that you figure out how to respond to any you get.
Here is an example:
use strict;
use DBI;
my $connect = DBI->connect('DBI:Oracle:', $dbuser, $dbpasswd);
my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle = `$cycle`";
my $query_handle = $connect->prepare($query);
$query_handle->execute();
#cmte_money = $query_handle->fetchrow_array();
print 'Money: ';
print #cmte_money;
if($#cmte_money >= 0)
{
print 'HI';
}
else
{
print 'NOOOO';
}
I define a constant variable $cycle, I think like this.
my $connect = DBI->connect('DBI:Oracle:',$dbuser,$dbpasswd);
# Tell the DBI that the query uses bind variable with ? (question mark)
my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle=?";
my $query_handle = $connect->prepare($query);
# Pass the value
$query_handle->execute($cycle); # assuming the variable is defined (otherwise it will pass as NULL into the query)
$cmte_money = $query_handle->fetchrow_array();
print 'Money: ';
print $cmte_money;
if($cmte_money > 0)
{
print 'HI';
}
else
{
print 'NOOOO';
}

Postgresql lowercase to compare data

I want to get the contents from a row in the Postgresql database and compare the lowercase version of it to a lowercase version of a user input to check if it exists in the database.
i tried:
"SELECT LOWER(name) FROM user_names WHERE name LIKE '%$search%' ORDER BY name ASC"
but that make query not working at all.
EDIT
I am trying to implement an autocomplete Jquery UI like here:
http://jqueryui.com/demos/autocomplete/#remote
for search box (for names)
using javascript and php.
php code:
$search = ($_GET['term']);
if (!$con)
{ die('Could not connect: ' . pg_last_error ());}
else
{
$sql = "SELECT name FROM users_table WHERE name LIKE '%$search%' ORDER BY name ASC";
$result = pg_query($sql);
$json = '[';
$first = true;
while ($row = pg_fetch_array($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;
exit();
}
JavaScript code:
$(document).ready(function()
{
$('#auto').autocomplete(
{
source: "./file.php",
minLength: 3
})
})
all above work great.. exactly like in Demo here: http://jqueryui.com/demos/autocomplete/#remote
my problem is that the names in database stored in Uppercase (e.g. LORI)
and of course the user prefers to insert a lowercase in search box to search for name (e.g. lori). but since it stored in uppercase, i need to convert it.
i tried as your suggestion :
$sql = "SELECT LOWER(name) FROM users_table WHERE name ILIKE '%$search%' ORDER BY name ASC";
then i got an empty drop down list!
pretty weird!
thanks in advance.
Google is your friend:
SELECT LOWER(name) FROM user_names
WHERE name ILIKE '%$search%' ORDER BY name ASC

Zend Framework Complex Where Statement

This method is published as offical example
->where("price < $minimumPrice OR price > $maximumPrice")
is such method safe?
want to write it as
->where("price < ? OR price > ?", $minimumPrice, $maximumPrice)
are there any poissibility?
and I can't split it into 2 where statements because plan to write query
->where("1 OR 2")
->where("3 OR 4")
Try this:
$query->where('(price < ?', $minPrice)
->orWhere('price > ?)', $maxPrice)
->where('some = ?', $some_other_variable);
will result:
where ((price < $minPrice) OR (price > $maxPrice)) AND (some = $some_other_variable)
Note the double (( )) in OR part
If I have complex WHERE clauses I use the db adapters' ->quoteInto() method like:
$where = '('
. $dbAdapter->quoteInto('price1 < ?', $price1)
. ' OR '
. $dbAdapter->quoteInto('price1 > ?', $price1)
. ')'
. ' AND '
. '('
. $dbAdapter->quoteInto('price2 < ?', $price2)
. ' OR '
. $dbAdapter->quoteInto('price2 > ?', $price2)
. ')'
;
$select->where($where);
Some times you will want to make SQL queries which have parenthesis around multiple where conditions that would be easily parsed with foreach, but you do not want to be bothered about string manipulation. For example, you would have a list of users with id's and that have to be of certain type, you can try this:
$select = $this->select();
$subWhere = $this->select();
foreach(array_keys($idArr) as $key => $value) {
$subWhere->orWhere('id=?', $value);
}
$select->where(implode(' ', $subWhere->getPart('WHERE')))->where('type=?', 'customer');
This will result in "SELECT * FROM table WHERE ((id=X) OR (id=Y) OR (id=Z)...) AND (type='customer');"
The idea developed a bit further, you could extend the Zend_Db_Table_Abstract:
public function subWhere($col, $binds, $operands, $andOr = 'OR' )
{
$subWhere = $this->select();
if(strtolower($andOr) == 'or') {
foreach($binds as $key => $value) {
$subWhere->orWhere($col.$operands[$key].'?', $value);
}
return implode(' ', $subWhere->getPart('WHERE'));
}
elseif (strtolower($andOr) == 'and') {
foreach ($binds as $key => $value) {
$subWhere->where($col.$operands[$key].'?', $value);
}
return implode(' ', $subWhere->getPart('WHERE'));
}
else {
return false;
}
}
And use it as:
$this->select()->where($this->subWhere($col, $binds, $operands));
Of course you should allow mixed $cols, $operands = array() defaulting as '=?' etc. but for the sake of simplicity I left that out. But I believe we should use native SQL functions like IN(), BETWEEN ... AND ..., NOT BETWEEN ... AND ...? Zend Framework doesn't make your life very easy though.
$select->where($db->quoteInto('field1 < ? OR', $minPrice)
. $db->quoteInto('field1 > ?', $maxPrice))
->where($db->quoteInto('field2 < ? OR', $value2)
. $db->quoteInto('field2 > ?', $value3));