CodeIgniter - query binding "IN" parameter - php

I have a following query in my CodeIgniter, which I'm trying to bind via parameter.
$q = "SELECT * FROM my_table WHERE id IN (?)"
$ids = "1,2,3,4";
$this->db->query($q, array($ids));
Above is not working, because the query binding treats $ids as string. How can I parameterize my query, but still be able to do "IN" operation?
EDIT
sorry, I have to use "raw SQL query". Above query is just a part of a much larger + complex query, which I can't use ActiveRecord for. Also I'm using Postgres.

Instead of string put it in array
$q = "SELECT * FROM my_table WHERE id IN (?)"
$ids = array(1,2,3,4);
$this->db->query($q, $ids);
You can achieve same thing like this without binding
Alternative
$ids = array(1,2,3,4);
$this->db->where_in('id',$ids);
$this->db->get('my_table');

Try this with where_in
$ids = array(1,2,3,4);
$this->db->select('*');
$this->db->from('my_Table');
$this->db->where_in('id',$ids);

$this->db->query($q, explode(',', $ids));
or
$this->db->where_in('id', explode(',', $ids))->get('my_table');
Active Records documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html#select

Use FIND_IN_SET like this
select * from table where FIND_IN_SET('$ids', id);

Try this code:
$ids = "('1','2','3','4')";
$q = "SELECT * FROM my_table WHERE id IN ".$ids;
$this->db->query($q);
you should use the
$ids = array('1','2','3','4');
$this->db->where_in('id', $ids);
The where_in is used in codignitor.

point is
$ids = "1,2,3,4";
$a = array($ids);
//$a[0] = "1,2,3,4";
//not $a[0]=1;$a[1]=2;$a[2]=3;$a[3]=4;
want to keep your style
$ids = "1,2,3,4";
$a = explode(",",$ids);

$q = "SELECT * FROM my_table WHERE id IN ?"
$ids = "1,2,3,4";
$this->db->query($q, explode(",", $ids));

Related

Select from database where a column equals any value in a variable

My database looks like this:
I have a variable that looks like this:
$following = "John, Sarah";
I would like to get the rows where the column 'username' is in the variable $following (in this case, John and Sarah). To do this, I had a look at the answer https://stackoverflow.com/a/1356018/5798798 which suggested I use IN in my query, which I have attempted:
$following = "John, Sarah";
$stmt = $con->prepare("SELECT * FROM events WHERE username IN ('$following')");
$stmt->execute();
while($row = $stmt->fetch()) {
echo $row['eventtype'];
}
The problem is that the query is returning no data. My desired result would be:
spoke walked
From what I suggested in comments to use the following:
$following = "John, Sarah";
$following = explode(", ", $following);
$string = implode(", ", $following);
It ended up that I didn't include the quotes for the implode()'ing.
The final solution was to add the single quotes in the first parameter for the implode() function:
$following = implode("','",$following);
$following = join("', '", $following);
join no more returns an array. It is a string now.
You can use like this:
$in = str_repeat('?,', count($following ) - 1) . '?';
$stmt = $con->prepare("SELECT * FROM events WHERE username IN ($in)");
$stm->execute($following);
with out using join you directly implode array by the following way
$stmt = $con->prepare('SELECT * FROM events WHERE username IN ("'. implode('","', $following).'")');
$stmt->execute();
while($row = $stmt->fetch()) {
echo $row['eventtype'];
}
Note: $following always should be in array

Multiple column where_in clause in codeigniter

Below is codeigniter single column where_in clause $this->db->where_in('x1',$val);
how can I pass multiple column in CodeIgniter where_in clause like below MySQL query select * from tab1 where (col1,col2) in ((1,2),(2,3))
Any help appreciated
Assume your data array is like this(should be)
$val1 = array(1,2);
$val2 = array(2,3);
And query should be
$this->db->select('*');
$this->db->from('tab1');
$this->db->where_in('col1',$val1);
$this->db->or_where_in('col2',$val2);
$query = $this->db->get();
$result = $query->result_array();
Or else you can use
$this->db->query("select * from tab1 where (col1,col2) in ($val1,$val2)");
"$arr_1 = some_array;"
"$arr_2 = some array;"
If they are the same array just replace $array_2 with $arr_1
$result = $this->db->select('*')->where_in('col1',$arr_1)->where_in('col2',$arr_2)->get('tab1')->result_array();
OR
$result = $this->db->select('*')->where_in('col1',$arr_1)->or_where_in('col2',$arr_2)->get('tab1')->result_array();

Pass an array as parameters to SQL procedure

I have SQL procedure in which I'm using an IN statment. It goes like this:
SELECT * FROM costumers WHERE id IN('1','2','12','14')
What I need to do is pass the values in to the IN statment as parameter which is an array in php, rather than hard-coded. How can I do that?
You can implode on this case:
$array = array('1','2','12','14');
$ids = "'".implode("','", $array) . "'";
$sql = "SELECT * FROM `costumers` WHERE `id` IN($ids)";
echo $sql;
// SELECT * FROM `costumers` WHERE `id` IN('1','2','12','14')
or if you do not want any quotes:
$ids = implode(",", $array);
You can use PHP function Implode
$array = array("1","2","12","14");
$query = "SELECT * FROM costumers WHERE id IN(".implode(', ',$array).")"
implode() is the right function, but you also must pay attention to the type of the data.
If the field is numeric, it is simple:
$values = array(1. 2, 5);
$queryPattern = 'SELECT * FROM costumers WHERE id IN(%s)';
$query = sprintf($queryPattern, implode(', ',$values));
But if it's a string, you must play with single and double quotes:
$values = array("foo","bar","baz");
$queryPattern = 'SELECT * FROM costumers WHERE id IN("%s")';
$query = sprintf($queryPattern, implode('", "',$values));
This should do the trick
$array = array('1','2','12','14');
SELECT * FROM `costumers` WHERE `id` IN('{$array}');
Try imploding the php into an array, and then interpolating that string into the SQL statement:
$arr = array('foo', 'bar', 'baz');
$string = implode(", ", $arr);
SELECT * FROM customers WHERE id in ($string);
use PHP's join function to join the values of an array.
$arr = array(1,2,12,14);
$sql = "SELECT * FROM costumers WHERE id IN(" . join($arr, ',') . ")";

String from Database into an Array

I have a field in my database which holds id's. An example would be: 1,2,3,4,5
I basically need to take that string and make it into 1 array so I can do a query with: WHERE id IN ($string_array).
PHP: explode - Manual
$string = "1,2,3,4,5";
$array = explode(",", $string);
$query = "SELECT * FROM `table` WHERE id IN (".$string.")";
$query = mysql_query($query);
I think this is what you're looking for:
$array = explode(",",$string)

Zend Framework DB Adapter fetchCol problem with "IN"

When making selects using the fetchCol method of the Zend_Db_Adapter class, queries are not working as I expected eg: (where $db is a reference to a DB_Adapter)
$ids = array(1,2,3,4);
$idString = implode(",", $ids);
$query = "SELECT id FROM some_table WHERE id IN (?)";
$result = $db->fetchCol($query, $idString);
You would expect this to return an array of ids that matched the idString, but it only returns an array with a single item - the first id matched. If I were to rewrite it like this there would be no problem:
$ids = array(1,2,3,4);
$idString = implode(",", $ids);
$query = "SELECT id FROM some_table WHERE id IN ($idString)";
$result = $db->fetchCol($query);
Is the expected behaviour or a bug in ZF? The main problem I have with it is it isn't an obvious error to track, no functionality is broken I just have fewer results.
ZF is clever enough to know what to with arrays, so all you need is pass in the array itself, skip the implode:
$query = "SELECT id FROM some_table WHERE id IN (?)";
$result = $db->fetchCol($query, array($ids));
with your code, since you are passing in a string it gets quoted, so the query you are running ends up being something like this:
SELECT id FROM some_table WHERE id IN ('1, 2, 3, 4')
Try:
$query = "SELECT id FROM some_table WHERE id IN (?)";
$result = $db->fetchAll($query, $idString);
OR
create a DbTable for 'sometable'
class SomeTable extends Zend_Db_Table_Abstract {
protected $_name = 'sometable';
}
Fetch results like this
$table = new SomeTable();
$select = $table->select();
$select->where('id IN (?)', $idString );
$result = $table->fetchAll( $select );
See following POST as well:
Zend Framework: Proper way to interact with database?
Try this:
$ids = array( 1, 2, 3 );
$db->fetchCol( 'SELECT id FROM some_table WHERE id IN (' . str_repeat( '?,', sizeof( $ids )-1 ) . '?)', $ids );
you can alse do something like this:
$db->fetchCol( 'SELECT id FROM some_table WHERE id IN (' . $db->quoteInto( '?', $ids ) . ')' );

Categories