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

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));

Related

How to use SQL raw query in Laravel

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

CodeIgniter parameterize integer and string

$code = Array(1,2,3,4)
$sql = "SELECT * FROM Table1 WHERE Field1 IN (?)";
$query = $this->db->query($sql, array($code));
$this->db->last_query() will show
"SELECT * FROM Table1 WHERE Field1 IN ('1,2,3,4')"
How can I remove the single quote in the IN condition?
Even if the $code is array of strings, example
$code = Array('This one', 'Next code', 'And this')
the statement will be:
"SELECT * FROM Table1 WHERE Field1 IN ('This one, Next Code, And This')"
Am I missing something ?
TIA.
You can use this simple and alternate way
$this->db->where_in('Field1',$code);
$this->db->get('Table1');
From codeigniter active record manual
$this->db->where() accepts an optional third parameter. If you set it
to FALSE, CodeIgniter will not try to protect your field or table
names with backticks.
$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
So, put a 3rd parameter on a where clause with FALSE
Then your query should be
$this->db->select('*')
->where('Field1 IN('.$code.'),NULL,FALSE)
->get('Table1');

Write union query in codeigniter style

How can I write the following query in Codeigniter style.
SELECT COUNT(`id`) AS reccount
FROM
(SELECT `id` FROM table1
WHERE tid= '101' AND `status` = 1
UNION ALL
SELECT `id` FROM table2
WHERE tid= '101' AND `status` = 1
UNION ALL
SELECT `id` FROM table3
WHERE tid= '101' AND `status` = 1) t
I have used the following way to execute it.
Is it the only correct way or do you have any suggestion to improve it?
$q = $this->db->query(SELECT COUNT(`id`) AS reccount
FROM
(SELECT `id` FROM table1
WHERE tid= '101' AND `status` = 1
UNION ALL
SELECT `id` FROM table2
WHERE tid= '101' AND `status` = 1
UNION ALL
SELECT `id` FROM table3
WHERE tid= '101' AND `status` = 1) t ");
Since CodeIgniter 3 it's been introduced in Active Record the function get_compiled_select() that gives the query string without actually executing the query.
This allows #MDeSilva method to use less resources, being adapted as follows:
function get_merged_result($ids){
$this->db->select("column");
$this->db->distinct();
$this->db->from("table_name");
$this->db->where_in("id",$model_ids);
$query1 = $this->db->get_compiled_select(); // It resets the query just like a get()
$this->db->select("column2 as column");
$this->db->distinct();
$this->db->from("table_name");
$this->db->where_in("id",$model_ids);
$query2 = $this->db->get_compiled_select();
$query = $this->db->query($query1." UNION ".$query2);
return $query->result();
}
You can use CI to generate a union query. However, latest versions made this much harder than before.
DB has a method called _compile_select, in previous versions of CI it was public, however now it is protected so you can't just call $this->db->_compile_select() from your controller. In order to do this properly one could:
Create custom loader class to be able to extend core/database classes (i.e. load MY_DB_active_record instead of CI_DB_active_record).
Create custom activerecord class, with just one method:
public function compile_select() {
return $this->_compile_select();
}
In your controller, create all necessary queries, compile them into a string array using our public method compile_select()
Join the array into single query: '(' . implode(') UNION (', $queries) . ')'. You can also wrap this into a separate method inside your custom AR class.
function get_merged_result($ids){
$this->db->select("column");
$this->db->distinct();
$this->db->from("table_name");
$this->db->where_in("id",$model_ids);
$this->db->get();
$query1 = $this->db->last_query();
$this->db->select("column2 as column");
$this->db->distinct();
$this->db->from("table_name");
$this->db->where_in("id",$model_ids);
$this->db->get();
$query2 = $this->db->last_query();
$query = $this->db->query($query1." UNION ".$query2);
return $query->result();
}

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 *.

Using Mysql WHERE IN clause in codeigniter

I have the following mysql query. Could you please tell me how to write the same query in Codeigniter's way ?
SELECT * FROM myTable
WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B')
AND code!='B'
You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php
Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now subquery writing in available
And now here is your query with active record
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
$this->db->_reset_select();
// And now your main query
$this->db->select("*");
$this->db->where_in("$subQuery");
$this->db->where('code !=', 'B');
$this->db->get('myTable');
And the thing is done. Cheers!!!
Note : While using sub queries you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Watch this too
How can I rewrite this SQL into CodeIgniter's Active Records?
Note : In Codeigntier 3 these functions are already public so you do not need to hack them.
$data = $this->db->get_where('columnname',array('code' => 'B'));
$this->db->where_in('columnname',$data);
$this->db->where('code !=','B');
$query = $this->db->get();
return $query->result_array();
Try this one:
$this->db->select("*");
$this->db->where_in("(SELECT trans_id FROM myTable WHERE code = 'B')");
$this->db->where('code !=', 'B');
$this->db->get('myTable');
Note: $this->db->select("*"); is optional when you are selecting all columns from table
try this:
return $this->db->query("
SELECT * FROM myTable
WHERE trans_id IN ( SELECT trans_id FROM myTable WHERE code='B')
AND code!='B'
")->result_array();
Is not active record but is codeigniter's way http://codeigniter.com/user_guide/database/examples.html
see Standard Query With Multiple Results (Array Version) section
you can use a simpler approach, while still using active record
$this->db->select("a.trans_id ,a.number, a.name, a.phone")
$this->db->from("Name_Of_Your_Table a");
$subQueryIn = "SELECT trans_id FROM Another_Table";
$this->db->where("a.trans_id in ($subQueryIn)",NULL);

Resources