How to use SQL raw query in Laravel - laravel-5

SQL table:
SELECT id,
account_name,
parent_id
FROM
(SELECT id,
account_name,
parent_id,
CASE
WHEN id = 1 THEN #idlist := CONCAT(id)
WHEN FIND_IN_SET(parent_id, #idlist) THEN #idlist := CONCAT(#idlist, ',', id)
END AS checkId
FROM chart_of_account
ORDER BY id ASC) AS T
WHERE checkId IS NOT NULL
When I run this query in MySQL it works fine and the result is fetched perfectly, but when I run it in Laravel like this:
$accountId = DB::select('SELECT id,account_name,parent_id FROM
(SELECT id,account_name,parent_id,
CASE WHEN id = '.$account_id.' THEN #idlist := CONCAT(id)
WHEN FIND_IN_SET(parent_id,#idlist) THEN #idlist := CONCAT(#idlist,', ',id)
END as checkId
FROM chart_of_account
ORDER BY id ASC) as T
WHERE checkId IS NOT NULL');
it gives an error.
Argument 1 passed to Illuminate\\Database\\Connection::prepareBindings() must be of the type array, string given,

Try this:
$query = 'YOUR_QUERY_THE_BIG_ONE:)';
$result = DB::select($query,[]);
dd($result);
Optionally, you can use ? sign in your query wherever you are using user inputs to prevent mySQL injection issue and then provide their value in second parameter array of select function. One example would be:
$inputUserEmail = $request->input('email');
$query = 'SELECT * FROM users WHERE email=?';
$result = DB::select($query,[$inputUserEmail]);
dd($result);
I hope it gives you an idea

Related

sql query into raw query in laravel

I am new in laravel . I have laravel 5.7 version. and I have query
like
$emp_id = $request->user_id;
$User_workDone_record = DB::select(
DB::raw("
SELECT
(
SELECT access(id) FROM users where id = $emp_id
) as accessid,
a.date as date,
a.day as day,
a.projectname as projectname,
a.clientname as clientname,
task,
start,
(
SELECT users(id) FROM `users` where id = $emp_id
) as user,
end,
TIMEDIFF(end,start) as diff,
workdetails,
id,
rowpages
FROM
workdone as a
where
a.user = '$emp_id'
order by
a.date desc
")
);
but I got issue like :
SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION workdoneerp.access does not exist (SQL: SELECT(SELECT access(id) FROM users where id=9) as accessid, a.date as date,a.day as day,a.projectname as projectname,a.clientname as clientname,task,start,end,TIMEDIFF(end,start) as diff,workdetails,id,rowpages FROM workdone as a where a.user='9' order by a.date desc),
How to resolve ?
The problem is access(id) at the start of your SQL query.
The error is telling you the access() function does not exist in your database (workdoneerp).
To solve it you can
create the access() function
or don't use the access() function.

How to run a query string as SQL in laravel

I have a query in a variable and I want to run it :
$sql = "select id,
title,
parent_id
from (select * from categories
order by parent_cat_id, id) base,
(select #pv := '$category_id') tmp
where find_in_set(parent_cat_id, #pv) > 0
and #pv := concat(#pv, ',', id)";
How can run it as a query ?
I was able to run the query using the DB::select function:
$categories = DB::select($sql);
dd($categories);

How to use like clause in code iginiter query() WITH BIND PARAMS?

How to use like clause in code iginiter query() WITH BIND PARAMS?
Eg:
When I use
$query = 'SELECT mycol FROM mytable WHERE name LIKE %?';
$name = 'foo';
$db->this->query($query,array($name));
//the clause generated
//SELECT mycol FROM mytable WHERE id LIKE '%'foo'%'
//I expected this
//SELECT mycol FROM mytable WHERE id LIKE '%foo'
I don't to put param values inside query and use like below:
$query = 'SELECT mycol FROM mytable WHERE name LIKE '%foo';
Also I can not use $this->db->like() function as my query consists of:
INSERT IGNORE
and
INSERT INTO table SELECT col FROM table2;
Please suggests?
Thanks,
just use CodeIgniter Query Builder
$name = 'foo';
$query = $this
->db
->select('mycol')
->like('name', $name)
->get('mytable');
$query = 'SELECT mycol FROM mytable WHERE name LIKE ?';
$name = '%foo';
$this->db->query($query,array($name));
codeigniter will replace ? with 'params' value.
if you write this
$query = 'SELECT mycol FROM mytable WHERE name LIKE %?';
$name = 'foo';
//$db->this->query($query,array($name)); //you wrote this line wrong.
//it should be like this
$this->db->query($query,array($name));
it will produce
SELECT mycol FROM mytable WHERE name LIKE %'foo' //inverse comma after % ,actually before and after foo.
So your right way will be
$query = 'SELECT mycol FROM mytable WHERE name LIKE ?';
$name = '%foo';
$this->db->query($query,array($name));
It will produce
SELECT mycol FROM mytable WHERE name LIKE '%foo'
NOTE
You wrote this which is wrong
$db->this->query($query,array($name));
Right way
$this->db->query($query,array($name));

CodeIgniter and csv_from_result

I have getting data from a database and using
$query = $this->db->query("SELECT * FROM mytable");
echo $this->dbutil->csv_from_result($query);
however I want to change the name of my headers for the CSV for first_name is First Name...how would I go about doing that?
Thanks,
J
Try renaming the columns returned by the sql query:
$query = $this->db->query("
SELECT
first_name as 'First Name', last_name as 'Last Name'
FROM mytable
");
The downside is that you will have to list the columns instead of a simple *.

"SELECT ... IN (SELECT ...)" query in CodeIgniter

I have a query similar to this:
SELECT username
FROM users
WHERE locationid IN
(SELECT locationid FROM locations WHERE countryid='$')
$ is a value I get from end user.
How could I run this query in CodeIgniter? I can't find a solution in CodeIgnite's user guide.
Thank you so much for your answers!
Regards!
Look here.
Basically you have to do bind params:
$sql = "SELECT username FROM users WHERE locationid IN (SELECT locationid FROM locations WHERE countryid=?)";
$this->db->query($sql, '__COUNTRY_NAME__');
But, like Mr.E said, use joins:
$sql = "select username from users inner join locations on users.locationid = locations.locationid where countryid = ?";
$this->db->query($sql, '__COUNTRY_NAME__');
Note that these solutions use the Code Igniter Active Records Class
This method uses sub queries like you wish but you should sanitize $countryId yourself!
$this->db->select('username')
->from('user')
->where('`locationId` in', '(select `locationId` from `locations` where `countryId` = '.$countryId.')', false)
->get();
Or this method would do it using joins and will sanitize the data for you (recommended)!
$this->db->select('username')
->from('users')
->join('locations', 'users.locationid = locations.locationid', 'inner')
->where('countryid', $countryId)
->get();
Also, to note - the Active Record Class also has a $this->db->where_in() method.
I think you can create a simple SQL query:
$sql="select username from user where id in (select id from idtables)";
$query=$this->db->query($sql);
and then you can use it normally.

Resources