Using result of query to another query with IN() - php

I want to using result of query to another query with IN():
foreach($result as $key=>$value){
$id .= $value['id'];}
$sql2 = 'SELECT * FROM table where id IN($id)';
but the $id must be in 'id1, id2, id3' format. With $id .= $value['quiz_id'].' , ';
there is one comma after last id. How can I convert $id value to 'id1, id2, id3'.
Thanks in advance

Use an array:
$ids = array();
foreach($result as $key=>$value){
$ids[] = $value['id'];}
if (count($ids) > 0) // to avoid mySQL error on empty array
{
$ids_string = implode(",", $ids);
$sql2 = 'SELECT * FROM table where id IN($ids_string)';
}

foreach($result as $key=>$value){
$idArr[] = $value['id']
}
$idStr = implode(',', $idArr);
$sql2 = 'SELECT * FROM table where id IN($idStr)';
This will give you a comma separated string of ids that you can use in your IN() query.
Hope that helps

Related

How to create an SQL query using an array?

I have an Array with data and I want to create an SQL statement (In which I am going to use where to where in).
I have tried to make query but no success.
SQL will be like :
SELECT *
FROM documents
WHERE category = "recruitment"
AND sub_category in("forms")
OR category = "onboarding"
AND sub_category IN ("sop")
OR category = "policies"
AND sub_category IN("forms");
and Array is this :
{"Recruitment":["Forms"],"Onboarding":["Sop"],"Policies":["Forms"]}
I have tried this code :
foreach ($db_sub as $data=>$key){
$query = "where document.category = ".$data." or where document.sub_category in ('".$key."')";
}
But getting error array to string conversion. Plz help me.
Thanks in advance.
Error :
You are trying to concatenate a string with an array. Since your array's values are also arrays, you will have to convert them to string first. It could be done with the join function.
foreach ($db_sub as $data=>$key){
$query = "where document.category = ".$data." or where document.sub_category in ('".join(", ", $key)."')";
}
Now you shouldn't get array to string conversion error.
Use this example to create the required SQL query:
$whereClause = [];
$params = [];
foreach ($db_sub as $data => $key){
if (!is_array($key)) $key = [$key];
$whereClause[] = '(documents.category = ? AND documents.sub_category IN (?' . str_repeat(', ?', count($key) - 1) . '))';
$params[] = $data;
$params = array_merge($params, $key);
}
$whereClause = !empty($whereClause) ? 'WHERE ' . implode(' OR ', $whereClause) : '';
$query = "SELECT * FROM documents $whereClause";
$sth = $pdo->prepare($query);
$sth->execute($params);
$result = $sth->fetchAll();
Here variable $pdo is a PDO object

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, ',') . ")";

passing array of values in sql select statement of where condition

$sql = "select id from table_name ";
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row[id];
}
/* $data contains id's fetched from sql query from db.now i want to pass this id's(array of values) in $data array one by one to below select query in where condition and obtain desired result for each id.My question is how to pass an array of values to the below select statement I dont know how to do this.Any help is greatly appreciated.*/
$query = "select * from table where id1 = $data[] ";
$query = "select * from table where `id1` in (" . implode(', ', $data) . ")";
You should use the cross database function in Moodle called get_in_or_equal()
list($where, $params) = $DB->get_in_or_equal($data, SQL_PARAMS_NAMED);
$sql = "SELECT *
FROM {table}
WHERE $id {$where}"
$records = $DB->get_records_sql($sql, $params);
You can use the IN clause.
When you are totally sure you only have numeric values in your $data array. You can do the following:
$query = "select * from table where id1 IN(" . implode(',', $data) . ")";
You can use this:
$comma_separated = implode(",", $data);
if ($comma_separated != "")
$query = "select * from table where id1 IN($comma_separated)";

How to correctly parse an array for an SQL query

When you need to do something like this:
SELECT * FROM userinfo WHERE id in (18,2,6,4,5)
And the id array comes from another query like:
$ids = $conn->fetchAll('SELECT origin from action WHERE url = "'.$url.'" AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');
If I need to parse the array in order to give the right format to the query id do:
$norm_ids = '(';
foreach ($ids as $ids) {
$norm_ids .= $ids['origin'] .',';
}
$norm_ids = substr_replace($norm_ids ,"",-1) .')';
That outputs the ids like: (id1,id2,id3,id.......), so the I'll just: FROM userinfo WHERE id in ". $norm_ids;
But seems to ugly to me, is there a way to do this better?
You could do:
$idStr = rtrim(str_repeat('?,', count($ids), ',');
$query = 'SELECT * FROM userinfo WHERE id in (' . $idStr . ')';
and then use prepare():
$conn = $db->prepare($query);
$conn->execute($ids);
$res = $conn->fetchAll(...);
SELECT * FROM user_info WHERE id IN (SELECT origin from action ......) ....
Do you need the id's separate or can you combine them into 1 query?
perhaps something like:
SELECT * FROM userinfo WHERE id in (SELECT origin from action WHERE url = "'.$url.'" AND SUBSTRING(origin,1,3)<>"pct" GROUP BY origin');
this way you let the sql server do the work.
When i am faced with such situations, i use trim
$norm_ids_str = '';
foreach ($ids as $ids) {
$norm_ids_str .= $ids['origin'] .',';
}
$norm_ids = '(' . trim($norm_ids_str, ',') . ')';

How to query a database with an array? WHERE = 'array()'

I'm wondering how to query a database using an array, like so:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");
$friends is an array which contains the member's ID. I am trying to query the database and show all results where member_id is equal to one of the member's ID in the $friends array.
Is there a way to do something like WHERE = $friends[member_id] or would I have to convert the array into a string and build the query like so:
$query = "";
foreach($friends as $friend){
$query .= 'OR member_id = '.$friend[id.' ';
}
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");
Any help would be greatly appreciated, thanks!
You want IN.
SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');
So the code changes to:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");
Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string() to make sure there are no SQL injections.
Use the SQL IN operator like so:
// Prepare comma separated list of ids (you could use implode for a simpler array)
$instr = '';
foreach($friends as $friend){
$instr .= $friend['member_id'].',';
}
$instr = rtrim($instr, ','); // remove trailing comma
// Use the comma separated list in the query using the IN () operator
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ($instr)");
$query = "SELECT * FROM status_updates WHERE ";
for($i = 0 ; $i < sizeof($friends); $i++){
$query .= "member_id = '".$friends[$i]."' OR ";
}
substr($query, -3);
$result = mysql_query($query);

Categories