I have a query which fetches distinct user ids and I am trying to convert it into a comma separated string which I can pass into another sql query having IN in WHERE clause.
But I am getting an error saying array to string conversion.
$qry0="SELECT DISTINCT id FROM users ";
$res0=getData($qry0);
while($row0=mysqli_fetch_array($res0))
{
$data0 = $row0['id'];
}
And I'm trying to convert it as string like this:
$array = explode(",", $data0);
and pass it to another
$qry="SELECT * FROM login WHERE clientid IN(".$array.") ";
USe implode instead of explode:
$qry0="SELECT DISTINCT id FROM users ";
$res0=getData($qry0);
$data0 = array(); // initialize array first
while($row0=mysqli_fetch_array($res0))
{
$data0[] = $row0['id']; // create array like this
}
$array = implode(",", $data0); // use implode to convert array to string
The explode() function breaks a string into an array.To break array into string you need to use implode()
$qry0="SELECT DISTINCT id FROM users ";
$res0=getData($qry0);
$data0 = array();
while($row0=mysqli_fetch_array($res0))
{
$data0[] = $row0['id'];
}
$array = implode(",", $data0);
Related
I'm trying to bind an array in a raw WHERE IN query in the Laravel DB
example:
$arr = [1,2,3];
DB::select(DB::raw("select * from test1 WHERE id IN ? "), [$arr]);
for some reason the array is not being changed to the following query:
select * from test1 WHERE id IN (1,2,3)
does someone know if I can do this somehow?
try it in laravel:
$arr = [1,2,3];
$result = DB::table('test1')->whereIn('id', $arr)->get();
dd($result);
And use this one for your raw query:
$arr = [1,2,3];
$arr = join(",",$arr);
$result = DB::select(DB::raw("SELECT * FROM test1 WHERE id IN (".$arr.")"));
dd($result);
For preventing sql injection you use something like which i have mentioned below.
$arr = [1,2];
$arr = join(",",$arr);
$result = DB::select(DB::raw("SELECT * FROM test1 WHERE id IN (?,?)"),$arr);
dd($result);
it will be work for you.
$arr = [1,2,3];
$placeholders = implode(",", array_fill(0, count($arr), '?'));
DB::select("select * from test1 WHERE id IN ($placeholders)", $arr);
This example:
supports any length of an array
does not contain a cycle
passes arguments safely
In this example, I fill a new array with such a number of question marks equal to the array length. Then I glue the new array, separated by commas, and get "?,?,?, ...". Then I insert this substring between the parentheses operator "IN". And I pass the array of items itself as the second parameter of the select function. As a result, each element of the array of elements has its own placeholder in the "IN" operator.
or
DB::table("test1")->whereIn('id', $arr)->get();
https://laravel.com/docs/5.4/queries#where-clauses
or Eloquent :
$q= TestModel::where('id',$arr)->get();
Try:
$array = [2,5,9,7,5];
$arrPos = [];
$arrBind = [];
foreach ($array as $pos => $id) {
$arrPos[] = ":id_{$pos}";
$arrBind["id_{$pos}"] = $id;
}
$sql =
" SELECT * FROM test1 WHERE id IN (".implode(', ', $arrPos).") ";
$rs = DB::select($sql, $arrBind);
I slightly optimized #nilecrocodile code so that we don't need to construct array and create string from and it. Instead, we'll create placeholders string this way:
$placeholders = substr(str_repeat(', ?', count($arr)), 2);
DB::select("select * from test1 WHERE id IN ($placeholders)", $arr);
I am trying to build a function that will be given an array. and from this array, iterate through an entire table in the database trying to find a match. If it does find a match. I would like it to echo out the ID of that match from the database table.
If possible I would also like it to say if it found any close matches?
What's making this tricky for me is that it needs to match all values despite their order.
for example, if the function is given this array:
$array = array(1,2,3,4,5)`
and finds this array in the database:
$array = array(2,3,5,1,4)
it should consider this a match
Also, if it finds
array(1,2,3,4,5,6)
It should output this this as a match except for value 6.
Let me refrase your question, is this correct?
Based on an array of ID's, return all records whose ID's are in the array.
If so, use the IN operator:
SELECT *
FROM tableName
WHERE columnName IN (value1, value2, value3, etc.)
So first we need to transform the given array into a comma-seperated list:
$comma_seperated = implode(', ', $array);
Now we have a comma-seperated list we can use in our query:
$comma_seperated = implode(', ', $array);
$query = "SELECT *
FROM tableName
WHERE id IN (" . $comma_seperated . ")";
// execute query, don't use mysql_* functions, etc. ;)
You could use any of the options:
option 1:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM youtable WHERE id IN(".implode(",",$array).")";
option 2:
$array = array(1,2,3,4,5);
$query = "SELECT id FROM yourtable";//Select ids
Now iterate through query results, say results are stored in $query_results,
$result=array();
foreach($query_results as $row){
if(in_array($row['id'],$array)){
$result[] = $row['id'];
}
}
You can use array difference to get the result just run the code and you will understand
Case 1
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array1, $array2);
print_r($result);
Case 2
$array1 = array(1,2,3,4,5);
$array2 = array(1,2,3,4,5,6);
$result = array_diff($array2, $array1);
print_r($result);
And after that you can the count of $result and put it in your logic.
Case 1:
Maybe you can select the unique values from the database.
SELECT DISTINCT unique_values_that_need_for_compare_column FROM table
This SQL result will be the $databaseValues variable value.
Than iterate through the array that the function gets.
foreach ($functionArray as $value) {
if (in_array($value, $databaseValues)) {
// you have a match
echo $value;
}
}
Case 2:
Or you can make a query for every value:
foreach ($functionArray as $value) {
$query = "SELECT COUNT(*) as match FROM table WHERE unique_values_that_need_for_compare_column = " . intval($value);
// fetch the result into the $queryResult variable and than check
if ($queryResult['match']) {
// you have a match
echo $value;
}
}
I'm trying to put an array into a query but I doens't work. I'm tying it with implode() but then it gives me " Array to string conversion in ... on line 26". Why? With json_encode it worked out ...
Thanks for your help!
$sql = mysql_query("SELECT follows
FROM follow
WHERE follower LIKE '".$id."'") or die (mysql_error());
if(mysql_num_rows($sql) < 1){
echo "<br/>";
echo "Follow someone";
} else {
//Put all the id's of the users the user is following in an array.
$i = 0;
$user_follows = array();
while ( $row = mysql_fetch_assoc($sql) )
{
$user_follows[$i] = $row;
$i++;
}
$user_follows = implode(" , ", $user_follows);
echo $user_follows;
}
The second argument to implode must be an array of strings. But you're doing:
$user_follows[$i] = $row;
Since $row is an array, you're making an array of arrays (a 2-dimensional array), not an array of strings. That should be:
$user_follows[] = $row['follows'];
You don't need the $i variable, assigning to $array[] appends a new element to the array.
For the last 1 1/2 days I've been trying to store 16 row id's into a string and separate each id with a comma. The array I am getting is from MySQL. The error I am getting is
implode() function:passed invalid arguments
$str=array();
$string="";
while($row = mysql_fetch_row($result))
{
$user_id=$row;
$str=$user_id;
foreach($str as $p=>$v){
comma($v);
}
}
function comma($v){
$string= implode(",",$v); echo $string;
}
Try something like this:
$ids = array();
while ($row = mysql_fetch_assoc($result))
{
$ids[] = $row["UserID"];
}
echo implode(", ", $ids);
Replace "UserID" with the columnname of the id in your table.
So: first you build the array, next you implode the array into a string.
There is my solution:
SELECT GROUP_CONCAT(UserID) as string FROM Users;
For this function the delimiter is ',' by default.
$query = 'SELECT id FROM your_table';
$rs = mysql_query($query);
$row = mysql_fetch_array($result);
return implode(',', $row);
the result 1,2,3...
This code is reading from mysql db tables and should return few names. But each name is sent as separated string. I need it in one string. Here is code:
<?php
session_start();
function prList($REQUEST){
include ('into_sql.php');
mysql_select_db("db394771350", $conn);
$usr = $REQUEST["usnm"];
$fID = $REQUEST["friendID"];
$sql = mysql_query("SELECT * FROM users WHERE username='$usr'");
$a=mysql_fetch_array($sql);
$uID = $a["id"];
$res1 = mysql_query("SELECT * FROM friends WHERE friendID='$uID' AND accept='0'");
while($b=mysql_fetch_array($res1)){
$fuID = $b["userID"];
$res2 = mysql_query("SELECT * FROM users WHERE id='$fuID'");
while($c=mysql_fetch_array($res2)){
$usrn = $c["username"];
$array = array("$usrn");
encode($array);
}
}
}
?>
This is output:
["rhys"]["alexroan"]["bobjosh"]["xc.j.gingex"]["tom"]
$usrn = "";
while($c=mysql_fetch_array($res2)){
$usrn .= $c["username"];
}
echo $usrn;
How is the function encode defined?
I would suggest replacing $array = array("$usrn"); by $array[] = $c["username"] and at the end just implode all entries into one string via `$string = implode($array)
Why don't you just concatenate results ?
$result = "";
$i = false;
while ($c=mysql_fetch_array($res2)){
if ($i)
$result .= ' ';
$result .= $c["username"];
$i = true;
}
echo $result;
Check this out may be helpfule forl
FIND_IN_SET(str,strlist)
Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function does not work properly if the first argument contains a comma (“,”) character.
mysql> SELECT FIND_IN_SET('b','a,b,c,d');
-> 2