Zend: How to use 'not equal to' in WHERE clause? - zend-framework

I am using following zend code to select all data from a table where verified=1 and it is working for me.
$table = $this->getDbTable();
$select = $table->select();
$select->where('verified = 1');
$rows = $table->fetchAll($select);
No I want to select all data from that table where verified is not equal to '1'. I have tried the following ways but it is not fetching data.
$select->where('verified != 1');
$select->where('verified <> 1');
$select->where('verified != ?', 1);
Data structure for 'verified' column:
Field: verified
type: varchar(45)
Collation: utf8_bin
NULL: Yes
Default: NULL
Any idea that how to use 'not equal to' operator in WHERE clause in Zend? Thanks

$select->where('verified != ?', 1);
Real worls query example:
$query = $this->getDb()->select();
$query->from('title', array('title_id' => 'id', 'title', 'production_year', 'phonetic_code'))
->where('kind_id = 1')
->where('title = ?', trim($title))
->where('production_year != ?', '2009')
->limit(1)
;
Selects movies info from IMDB database. Works fine.

MySQL supports a custom operator <=> which returns true if the operands are equal or both null. It returns false if they are different, or if one operand is null.
$select->where('verified <=> 1');
This operator is non-standard. Standard SQL has syntax: IS NOT DISTINCT FROM that works just like MySQL's <=>.

Since your column is a varchar perhaps try where verified != '1' or verified is null

Can you show us the table structure for the table you are querying? Is the column verified an int or string? Also try printing the SQL statement that ZEND builds, see the echo line below.
$table = $this->getDbTable();
$select = $table->select();
$select->where('verified = 1');
echo sprintf("sql %s",$select);
$rows = $table->fetchAll($select);

Try :
$select->where('verified != ?', '1');
put quotation marks around the value. It is working for me.

Related

DB2 SQL Query Filtering rows based on multiple fields

I need to write a query based on the following conditions:
Within one table, the following condition must be met:
table name: DLS_RBM_RBI
columns within the table
RBM_3_CD must be blank
If RBM_3_CD is blank, then RBM_2_CD must be 1
If RBM_3_CD is blank and RBM_2_CD is blank, then RBM_1_CD must be 1
How would these conditions be coded in a SQL statement? In an IF within a where clause or case in a select?
I tried using a where clause with these conditions.
AND (D.RBM_3_CD = '')
OR (D.RBM_3_CD = '' AND D.RBM_2_CD = '1')
OR (D.RBM_3_CD = '' AND RBM_2_CD = '' AND RBM_1_CD = '1')
The first statement
AND (D.RBM_3_CD = ' ')
negates the need for the second and third. There's no way for the first statement to false while the second or third are true.
try this instead
where D.RBM_3_CD = ' '
and ( (D.RBM_3_CD = '' AND D.RBM_2_CD = '1')
or (D.RBM_3_CD = '' AND RBM_2_CD = '' AND RBM_1_CD = '1')
)

Covert SQL query to TYPO3 query builder?

How to convert SQL query to TYPO3 query builder.
SELECT * FROM tableName ORDER BY (CASE WHEN DATE(dateColumn) < DATE(GETDATE()) THEN 1 ELSE 0
END) DESC, dateColumn ASC
enter link description here
Same functionality i need in typo3 query builder.
To get the sql query you posted, you can do it like following:
// little helper function to debug querybuilder,
// queries with parameter placeholders
function debugQuery(QueryBuilder $builder)
{
$preparedStatement = $builder->getSQL();
$parameters = $builder->getParameters();
$stringParams = [];
foreach ($parameters as $key => $parameter) {
$stringParams[':' . $key] = $parameter;
}
return strtr($preparedStatement, $stringParams);
}
// get querybuilder
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionByName('Default')
->createQueryBuilder();
// build query
$queryBuilder
->select('*')
->from('table')
->getConcreteQueryBuilder()->orderBy(
'(CASE WHEN DATE('
.$queryBuilder->quoteIdentifier('dateColumn')
.') < DATE(GETDATE()) THEN 1 ELSE 0 END)',
'DESC'
)
;
$queryBuilder->addOrderBy('dateColumn', 'ASC');
// build query
$sql = debugQuery($queryBuilder);
The generates following sql query:
SELECT
FROM `table`
ORDER BY
(CASE WHEN DATE(`dateColumn`) < DATE(GETDATE()) THEN 1 ELSE 0 END) DESC,
`dateColumn` ASC
Some note beside:
To my knowlage GETDATE() is not a valid mysql method, more MSSQL. Eventually you want CURRENT_DATE() instead.
edit #1
Not tested/run .. just created the sql string to match what you provided. So don't blame me if provided sql query is wrong itself.

Why selectrow_array does not work with null values in where clause

I am trying to fetch the count from SQL server database and it gives 0 for fields with null values. Below is what I am using.
my $sql = q{SELECT count(*) from customer where first_name = ? and last_name = ?};
my #bind_values = ($first_name, $last_name);
my $count = $dbh->selectrow_array($sql, undef, #bind_values);
This returns 0 if either value is null in the database. I know prepare automatically makes it is null if the passed parameter is undef, but I don't know why it's not working.
So here is weird observation. When I type the SQL with values in Toda for SQL server, it works :
SELECT count(*) from customer where first_name = 'bob' and last_name is null
but when I try the same query and pass values in the parameter for the first_name = bob and the last_name {null} . it does not work.
SELECT count(*) from customer where first_name = ? and last_name = ?
For NULL in the WHERE clause you simply need a different query. I write them below each other, so you can spot the difference:
...("select * from test where col2 = ?", undef, 1);
...("select * from test where col2 is ?", undef, undef);
...("select * from test where col2 is ?", undef, 1);
...("select * from test where col2 = ?", undef, undef);
The first two commands work, stick to those. The third is a syntax error, the fourth is what you tried and which indeed does not return anything.
The DBI manpage has a section of NULL values that talks about this case a bit more.
So, here it is what I did. I added or field is null statement with each field if the value is undef.
my $sql = q{SELECT count(*) from customer where (first_name = ? or (first_name is null and ? = 1)) and (last_name = ? or (last_name is null and ? = 1))};
my #bind_values = ($first_name, defined($first_name)?0:1, $last_name, defined($last_name)?0:1);
my $count = $dbh->selectrow_array($sql, undef, #bind_values);
If anyone has better solution please post it.

how do i write not equal to in a doctrine where clause?

I hope someone can help me, i'm writing a custom query in my repository and i'd like to do the below:-
$query = $this->_em->createQueryBuilder()
->select('a')
->from('entity', 'a')
->where('a.deleted not 1') /// how do you write NOT??? i've tried <> etc
->getQuery();
How do i perform the above?
Thanks
Andrew
Francesco's answer is correct. It all depends on your will to use either the expression builder or a high level solution.
For your particular case you can choose one of the two.
Expression builder:
$queryBuilder = $this->_em->createQueryBuilder();
$expr = $queryBuilder->expr();
$query = $queryBuilder
->select('a')
->from('entity', 'a')
->where($expr->neq('a.deleted', 1))
->getQuery();
For high level solution see Rawkode's answer. Except changing the != to <> or using a.deleted = 0.
Better yet would be parametrizing this with Doctrine
->where('a.deleted = :deleted')
->setParameter('deleted', false);
Just use neq() like in the following example:
$query = $repository->createQueryBuilder('t');
$expr = $query->expr();
$orx = $expr->orX();
$orx->add($expr->neq('t.pageTitle', $expr->literal('value1')));
$orx->add($expr->neq('t.metaDescription', $expr->literal('value2')));
$query->andWhere($orx);
The above code produces:
AND (
t1_.page_title <> 'value1'
OR t1_.meta_description <> 'value2'
)
$query = $this->_em->createQueryBuilder()
->select('a')
->from('entity', 'a')
->where('a.deleted != 1') /// how do you write NOT??? i've tried <> etc
->getQuery();
'!=' means not equal
!= means not equal to
!=== means not identical to
$queryBuilder = $repository->createQueryBuilder('a');
$query = $queryBuilder
->where($queryBuilder->expr()->notIn('u.id', 1)
->getQuery();
I'm not sure about not equal operator in query building. But, this may help you.
BTW, I'm also looking for better answer.

[zend][db] fetchAll with multiple variables

I'm trying to use fetchAll on a query that has 2 variables. I can't figure out the syntax.
I can manage with only 1 variable:
$sql = "SELECT * FROM mytable WHERE field1 = ?";
$this->_db->fetchAll($sql,$value1); # that works
However I'm having some issues when query has multiple variables
$sql = "SELECT * FROM mytable WHERE field1 = ? AND field2 = ?";
$this->_db->fetchAll($sql,$value1,$value2); # doesn't work
$this->_db->fetchAll($sql,array("field1"=>$value1,"field2"=>$value2)); # doesn't work either
The reason why I want to use ? instead of placing the variables directly into the query is that I've learned that using ? allows for the query to be compiled generically by the db engine and improves performances.
There are two types of parameter, named parameters and positional parameters. You're mixing the two types and that won't work.
Named parameters match a placeholder by name. Names are started with the : symbol. The parameter names are not the same as the names of the columns you happen to use them for. You supply parameter values in an associative array, using the parameter name (not the column name) as the array keys. For example:
$sql = "SELECT * FROM mytable WHERE field1 = :param1 AND field2 = :param2";
$this->_db->fetchAll($sql,array("param1"=>$value1,"param2"=>$value2));
Positional parameters use the ? symbol for the placeholder. You supply parameter values using a simple (non-associative) array, and the order of values in the array must match the order of parameter placeholders in your query. For example:
$sql = "SELECT * FROM mytable WHERE field1 = ? AND field2 = ?";
$this->_db->fetchAll($sql,array($value1,$value2));
Most brands of SQL database natively support only one style or the other, but PDO attempts to support both, by rewriting the SQL if necessary before preparing the query. Since Zend_Db is modeled after PDO, Zend_Db also supports both parameter styles.
This question is a bit old, but I thought I'd just add to it for reference sake.
I would recommend starting to use Zend_Db_Select with Zend_Db. I've been doing a lot with Zend_Db lately. More from Zend_Db_Select reference guide.
Lets assume you have a Zend_Db adapter: $this->_db
# this will get the Zend_Db_Select object
$select = $this->_db->select();
# now you build up your query with Zend_Db_Select functions
$select->from('mytable');
$select->where('field1 = ?', $field1);
$select->where('field2 = ?', $field2);
[...]
# echo to see the SQL (helps in debugging)
# SELECT * FROM mytable WHERE field1 = ? AND field2 = ? [...]
echo '<p>My SQL: ' . $select . '</p>';
# Execute the SQL / Fetch results
$results = $select->query()->fetchAll();
That's the basics from your given example, but the Zend Framework reference guide on the select object has a lot of good information on how to build even more complex queries with JOINS, UNIONS, GROUP BY, LIMIT, HAVING, etc.
If you wanted to use an alias name for a table or parameters, you use an associative array with the alias name being the index value:
# SELECT p.* FROM products AS p
$select->from('p' => 'products');
If you want to return only selected fields, you add an array of field names as a second parameter:
# SELECT model FROM products
$select->from(products, array(model));
Actually, the above could should produce fully qualified SQL as:
SELECT 'products'.model FROM 'products'
but I wrote the above for brevity and clarity in the example.
One thing I just came across is using AND and OR in the WHERE condition.
# WHERE a = $a
$select->where('a = ?', $a);
# WHERE a = $a AND b = $b
$select->where('a = ?', $a);
$select->where('b = ?', $b);
# WHERE a = $a OR b = $b
$select->where('a = ?', $a);
$select->orWhere('b = ?', $b);
# WHERE a = $a AND b = $b
$select->orWhere('a = ?', $a);
$select->where('b = ?', $b);
Notice, that whatever the following "where" function you use, will combine with the previous statement as that operand. Ok, that sounded confusing.
If the second "where" is an "OR" it will be an "OR" conditional. If the second "where" is a "AND" the statement will be "AND".
In other words, the first WHERE function is ignored in terms of what condition it will use.
In fact, I just asked a question on Stack Overflow yesterday regarding doing a complex WHERE using select.
Hope that helps!
Cheers!
Try this:
$sql = "SELECT * FROM mytable WHERE field1 = ? AND field2 = ?";
$statement = $this->_db->query($sql,array("field1"=>$value1,"field2"=>$value2));
$data = $statement->fetchAll();
$this->_db must be an instance of Db adapter.
Heres the actual Zend way to code for this.
$sql = "SELECT * FROM mytable WHERE field1 = :param1 AND field2 = :param2";
$this->_db->fetchAll($sql,array("param1"=>$value1,"param2"=>$value2));
$where = $this->_db->select()
->from('mytable')
->where('field1 = ?',$value1)
->where('field2 = ?',$value2);
$rowSet = $this->_db->fetchAll($where);
This works great for me