Laravel: using WHERE CONCAT in query - mysql

I am pretty new to laravel and facing a problem building a query using CONCAT:
#From input
$password = $request->password;
#sql statement
UserMainTbl::where('username', '=', $username)->whereRaw('hashkey', '=', CONCAT('admin_id'.$password))
Table: UserMainTbl
Field: username, hashkey, admin_id
Got error:
Call to undefined function App\Http\Controllers\Auth\CONCAT()
------
Update:
I change my code and manage to stop the above error. But getting new error.
->where('hashkey', '=', DB::raw('concat(admin_id,"$password")'))
Column not found: 1054 Unknown column 'password123' in 'where clause' (SQL: select * from user_main_tbl where username = xxx and hashkey = concat(admin_id,password123) limit 1)
------
Update [Solve]:
My bad on this one. It is just a simple string. Here is the solution for future reference, if any. Lol:
->where('hashkey', '=', DB::raw('concat(admin_id,"'.$password.'")'))
Can someone help to point how can I do it right?
Many thanks.

I know you have solved the issue, but your solution can open up possibilities for SQL Injection if you don't escape the user input.
One way to tackle this is by adding a binding.
UserMainTbl::where('username', '=', $username)
->where('hashkey', '=',DB::raw('concat(admin_id,"?")'))
->addBinding($password);
https://laravel.com/docs/5.3/queries#raw-expressions

Always be careful in using RAW method in query builder since it's prone to SQL injections. I suggest to separate the concatenation of the "admin_id" and "password" and use the standard WHERE method to avoid the problem.

Related

Trouble with AND operator on Eloquent Raw query MySQL JSON

I am trying to figure out the correct syntax to add an AND operator to the following Eloquent Raw query in which I am querying a MySQL (5.7.9) table's JSON field. In doing so, I would like to be able to have case insensitivity capabilities.
After doing initial research as to how to achieve this, I have my code working in a basic way like this:
$users = User::whereRaw('lower(info_json->"$.full_name") like lower(?)', ["%{$user_name}%"])
But my goal is to add an AND operator to narrow down my results further with a non-JSON varchar column.
I have tried this (and other variations without success):
$users = User::whereRaw('lower(info_json->"$.full_name") like lower(?)', 'and user_type = admin', ["%{$user_name}%"])
Which gives me an error:
"Array to string conversion"
I have also tried:
$users = User::whereRaw('lower(info_json->"$.full_name") like lower(?) and user_type = admin', ["%{$user_name}%"])
Which give me the following error:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_type' in 'where clause'"
Other similar variations that have not resulted in errors have yielded too many or too few results.
How can I successfully adjust my syntax to query an additional non-JSON field with the correct results? Also, is doing a raw query like this the most effective way to do so with Eloquent, MySQL (5.79) and Laravel 5.6?
Thank you for any and all help/direction offered! :)
I think you should do something like
$users = User::where(DB::raw('lower(info_json->"$.full_name")', 'like', DB::raw('lower(%{$user_name}%)'))
->where('user_type', '=', 'admin')
Probably I have some sintax error but main idea is to use DB::raw to help you with your query.
I figured it out. My syntax should have looked like this:
$users = User::whereRaw('lower(info_json->"$.full_name") like lower(?)', ["%{$user_name}%"])->where('user_type', '=', 'admin')->get();
Thanks to those who assisted with this! Like a lot of syntax/coding problems, taking a little break from it helped me to figure it out quite quickly when I returned to it.

Retrieve data from a specific row

I'm trying to get data from a specific row from my database.
And I get the error:
Unknown column 'Apalm' in 'where clause'
This is my code:
$naam = $_GET['naam'];
$result = mysql_query("SELECT * FROM planten WHERE naam = $naam")
or die(mysql_error());
And the picture below shows my database.
It seems like the script thinks the row is called "Apalm". But I clearly stated to search in 'naam'?
This is probably very easy to fix, but I just can't seem to find it on Google.
So please help me, or point me in the right direction. I'm very eager to learn this!
Thanks in advance!
naam column seems to be a text, so enclose its value between single quotes within the sql code as well:
"SELECT * FROM planten WHERE naam = '$naam'"
However, pls consider using either proper escaping or prepared statements to prevent sql injection.

how to get Even/Odd id numbers from a database table in codeigniter

I am new in codeigniter and just stacked in a query to solve a report for an emergency project. Please help me Codeigniter's Experts.
I have a large database table and wants to show only Odd/Even Data rows from that table which will filtered by a table Field named is "sale_id". I tried it in PHPMyadmin in raw coding and it's worked for me. But can not apply in Codeigniter.
SELECT * FROM ospos_pak_sub_cat WHERE id %2 =0;
Worked for me in raw PHP Coding. How can I use it in Codeigniter. I used a Where Condition already on that query and now want to add the new query.
Existing Where condition is given below, which is working fine.
$this->db->where('sale_date BETWEEN "'. $inputs['start_date']. '" and "'. $inputs['end_date'].'"');
It is working and I tried the code below to get the solution which is not working and getting error.
$this->db->where('sale_id %2'=> 0);
Getting error with this line. says--
Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW)
Please help me to get the solutions. Thanks in Advance.
In your Model, just write the query like that:
$this->db->select('*');
$this->db->from('ospos_pak_sub_cat');
$this->db->where('sale_id %2=', 0);
$query_result = $this->db->get();
$result = $query_result->result();
You missed the '=' in your code. Hope, it will work.
in SQL the % character is a wildcard rather than a modulo which would explain your error. you can use the MOD function instead http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_mod
so the resulting code would be :
$this->db->where('MOD(sale_id ,2) => 0');
I am not sure but i think it will work try this line
$this->db->where('sale_id %2',0);
As you mentioned, you can add the new condition in existing where condition as like below
$this->db->where('(sale_date BETWEEN "'. $inputs['start_date']. '" and "'. $inputs['end_date'].')" and ((sale_id % 2) = 0)');

How to customize error message on Symfony2

I'm trying to use DQL to create a query between a ManyToMany relation, here a snippet of my code:
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery("SELECT * FROM TestGroupBundle:Question");
It's a really basic SQL line, but I always get this weird error:
[Syntax Error] line 0, col 7: Error: Expected IdentificationVariable | StateFieldPathExpression | AggregateExpression | "(" Subselect ")" | ScalarExpression, got '*'
500 Internal Server Error - QueryException
Can someone tell me what does it mean please and how to fix it ? Thanks
You're mixing up SQL and DQL. There's no "*" in DQL since you're working with your object model. The proper syntax would be "SELECT q FROM TestGroupBundle:Question q". The result is wrapped in \Doctrine\Common\Collections\ArrayCollection object. You can iterate over the object to get your results.
There's one important thing to keep in mind about DQL:
A common mistake for beginners is to mistake DQL for being just some form of SQL and therefore trying to use table names and column names or join arbitrary tables together in a query. You need to think about DQL as a query language for your object model, not for your relational schema.
Doctrine doesn't always parse namespace shortcuts correctly. Try using the full namespace instead of TestGroupBundle:Question

Using a table-alias in Kohana queries?

I'm trying to run a simple query with $this->db in Kohana, but am running into some syntax issues when I try to use an alias for a table within my query:
$result = $this->db
->select("ci.chapter_id, ci.book_id, ci.chapter_heading, ci.chapter_number")
->from("chapter_info ci")
->where(array("ci.chapter_number" => $chapter, "ci.book_id" => $book))
->get();
It seems to me that this should work just fine. I'm stating that "chapter_info" ought to be known as "ci," yet this isn't taking for some reason. The error is pretty straight-forward:
There was an SQL error: Table 'gb_data.chapter_info ci' doesn't exist -
SELECT `ci`.`chapter_id`, `ci`.`book_id`, `ci`.`chapter_heading`,
`ci`.`chapter_number`
FROM (`chapter_info ci`)
WHERE `ci`.`chapter_number` = 1
AND `ci`.`book_id` = 1
If I use the full table name, rather than an alias, I get the expected results without error. This requires me to write much more verbose queries, which isn't ideal.
Is there some way to use shorter names for tables within Kohana's query-builder?
In Kohana 3 it is simply enough:
->from( array('table_name', 'alias') )
and this will create the query that contains:
FROM 'table_name' AS 'alias'
I have tested it and it works. Good luck.
$result = $this->db
->select("ci.chapter_id, ci.book_id, ci.chapter_heading, ci.chapter_number")
->from("'chapter_info' AS ci")
->where(array("ci.chapter_number" => $chapter, "ci.book_id" => $book))
->get();
That should work. As you must wrap the original table name in quotes first before the AS keyword and the new table name you want to shorten it to.
Try using the "as" keyword like ->from("chapter_info as ci"), maybe the query builder will recognize it this way.