Order clause with 'like' clause in Zend DB - php

Query:
select * from table_name ORDER BY name like 'C%' DESC;
This query work fine in MySql, but i am unable build the query using Zend DB.
I am getting error while executing.
PHP DB code:
$result = $this->getDefaultAdapter()
->select()
->from($this->_name,array('*'))
->order("name like 'C%' DESC")
->query()
->fetchAll();
Error:
Column not found: 1054 Unknown column 'name like 'C%'' in 'order clause'
Thanks in advance

Zend_Db_Select tries to delimit strings as column names, but it skips doing that if you pass an object of type Zend_Db_Expr instead of a string:
->order(new Zend_Db_Expr("name like 'C%' DESC"))->
There's also an undocumented shortcut: the column-delimiting function assumes that any string containing parentheses is very likely to be an expression instead of just a column name. So the following would work too:
->order( "(name like 'C%' DESC)" )->

I'm not familiar with zend but Try to rewrite your sql query in Zend like this
select *, (`name` like 'C%') as theFiled from table_name by theFiled desc;
Though i'm not so sure I guess that the Zend Code must be something like this,
$result = $this->getDefaultAdapter() ->select()
->from($this->_name,array('*', "theFiled" => "name like 'C%'") ->order("theFiled DESC")
->query() ->fetchAll();

Related

Applying string function in column Laravel 5.4

I'm using the latest Laravel 5.4
I am trying to make a simple query to search users by name. The query written for MySQL looks like this:
SELECT *
FROM users
WHERE upper(name) LIKE '%FOO%';
I'm trying to make it work with Eloquent. Things I've tried but failed:
User::where('upper(name)', 'LIKE', '%FOO%')->get()
DB::table('users')->where('upper(name)', 'LIKE', '%FOO%')->get()
Both fail with the following error:
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'upper(name)' in 'where clause' (SQL: select * from users where upper(name) LIKE %FOO%)'
The query seems to fail because Eloquent wraps the upper(email) statement with backticks (" ` ", " ` "). Is there a way to go around this issue or do I have to use a particular eloquent function to get convert a column to uppercase, lowercase, e.t.c?
Use DB::raw()
User::where(DB::raw('upper(name)'), 'LIKE', '%FOO%')->get()
It would generate query like this
"select * from `users` where upper(name) LIKE ?"
You can use whereRaw() in laravel to achieve this :
User::whereRaw("upper(name) LIKE '%FOO%'")
->get();

Setting a query result literal in Laravel query builder?

I am trying to set a column result literal with the Laravel query builder. By writing raw SQL I would achieve this with:
SELECT
`field1`,
`field2`,
'Test' AS `field3`
FROM `Test`;
Therefore MySQL will always return Test for column field3. I'm trying to do this with the query builder like select('field1', 'field2', '"Test" AS field3') but this doesn't seem to work. It will return an error that Test is not a column name.
Does anyone have an idea how I could do this?
You want the DB::raw() function:
->select('field1', 'field2', DB::raw("'Test' AS field3"))

Using DB::select() in Laravel with LIKE clause and a variable column name

In the docs,
$results = DB::select('select * from users where id = ?', array(1));
The Problem
I have a variable $column and $value and I want them to search the database based on what column like this:
$results = DB::select('select * from users where ? LIKE "%?%"', array($column, $value));
But this throws an error:
SQLSTATE[42P18]: Indeterminate datatype: 7 ERROR: could not determine data type of parameter $2 (SQL: SELECT * FROM test WHERE refno LIKE '%te%')
I tried hard-coding the value like this:
$results = DB::select('select * from users where ? LIKE "%te%"', array($column));
but it returns a blank array.
How do I do this? Please help.
EDIT:
The query is actually long (with multiple joins). So I prefer not to use the Query Builder style if possible. But if it's not possible, then I will just use Query Builder.
Info:
Laravel v4.2
PostgreSQL
It could be done in more Query Builder style, like that:
$results = DB::table('users')
->where($column, 'LIKE', '%' . $value . '%')
->get();
EDIT
The only reliable way how to do it with DB::select() is:
$results = DB::select("select * from users where ? LIKE '%?%'", array($column, $value));
It produces the right query, I checked it against the database, but also a blank array, or wrong results. Even if this method somehow worked, you still have to escape table and columns names manually, which is tedious and apparently does not work with ?. If you lets say had a $column named values this method would break, since values is a reserved word (at least in MySQL).
The Query Builder method is highly advised, because it also automatically adds SQL escapes to table and column names. Also it is is more portable across DB drivers. It also supports joins with ease. No need to use the method you wants.
the only way i find working
$phone = '%'.$phone.'%';
$seachbyphone = DB::select('SELECT * FROM user WHERE phoneno LIKE ?',[$phone]);
try this:
use App\User; //don't forget add this to header
$result = User::where('columnName', 'LIKE', "%$value%")->get();
LIKE '%?%'" is incorrect. It must be ? only as sql query only expects ? =>vacancy/placeholder for value. Not any single comma or wildcard.
So You need to add % sign with value not with ? =>(placeholder), and its safe as well.
That's why we need
$results = DB::select("select * from users where ? LIKE ?, [$column, '%'.$value.'%'.]);
I would not recommend DB::select() to anyone, even though you have perfectly valid SQL that works directly in the database engine Laravel produces peculiar errors with made-up error descriptions. Instead use DB::table('my_table')->select('...') instead.

Zend_Db_Adapter_Oracle: Select with ORDER BY, LIMIT & WHERE

I'm trying to select some records from an Oracle 11g Database. The Statement is used to implement some kind of "filter" function for an HTML Table.
Requirements: limit for paging and order the filtered results.
The query is created with Zend_Db_Select
*Works like a charm:*
$select->where('APPLICATIONS LIKE ?', '%MYAPP1%');
$select->where('APPLICATIONS NOT LIKE ?', '%GENESIS%');
$select->limit(20);
= 1 matching result (which is ok!)
The problem occurs when I try to order the filtered result:
$select->order('PATH ASC');
= 3 matching results ??
I think it has something to do with the query generated by Zend DB Select, it looks like this:
SELECT z2.*
FROM (
SELECT z1.*, ROWNUM AS "zend_db_rownum"
FROM (
SELECT "APPS".* FROM "APPS" WHERE (APPLICATIONS LIKE '%MYAPP1%') AND (APPLICATIONS NOT LIKE '%GENESIS%') ORDER BY "PATH" ASC
) z1
) z2
WHERE z2."zend_db_rownum" BETWEEN 1 AND 20
If I run the query without order everything is fine.
If I run the query without limit everything is fine.
If I run the query with order + limit -> wrong result.
If I take the statement and put the order after "BETWEEN 1 AND 20" it works like I want. But how to say Zend DB Select to change it?
Important: I'm doing the query against an Oracle VIEW, if I do it against a "table" it works too.
Obviously Oracle's interpretation of the query is not what the Zend framework intents:
Oracle seems to associate the ROWNUM with the row number count on the inner query before ordering, so the alias zend_db_rownum delivers wrong numbers in the where clause of the outer query.
Since we're not in control of the way the Zend framework generates the SQL in response to the limit() instruction, the only workaround I can think of is skipping the Zend limit() instruction, and instead doing something along the lines of:
$select->where('APPLICATIONS LIKE ?', '%MYAPP1%');
$select->where('APPLICATIONS NOT LIKE ?', '%GENESIS%');
$select->order('PATH ASC');
$sql = $select->__toString();
$sql = "select * from (" . $sql . ") where ROWNUM between 1 and 20";
$stmt = $db->query( $sql, array());
$result = $stmt->fetchAll();
Of course, this workaround is only legitimate in case you're not developing cross-DB, so your code doesn't have to be DB agnostic.
Meaning, you will restrict your solution to Oracle if you use my suggested workaround.
If you checked that there is no error in SQL generation, and really no different conditions in WHERE clause, it may be Oracle server bug. To check it, try it on different Oracle server version or different Oracle server patch level.

Having trouble with sql LIKE

I have the following query:
SELECT * FROM `alerts` WHERE `title` LIKE `%template%`
This should return at least 3 results with titles that includes the word 'template' but I'm getting the following error: -
1054 - Unknown column '%template%' in 'where clause'
As far as I can tell its syntactically correct and calling the correct column names. What am I missing?
Use single quotes for the %template%:
SELECT * FROM `alerts` WHERE `title` LIKE '%template%'

Categories