WHERE IN array binding in DB::raw laravel 5.4 - php

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

Related

Array of Values from SQL showing which exist and which don't

I couldn't think of a title, I know it's not good.
Basically, I'm going to have an array of values POSTed to me. These values will be integers.
So, let's say it will be 1,2,3,4,5 etc.. I've already figured out how to get their respective values from the database like such
$values = explode(",", $_GET['id']);
$placeholders = str_repeat('?, ', count($values) - 1) . '?';
$CheckQuery = $database->prepare("SELECT * FROM users WHERE the_id IN($placeholders)");
$CheckQuery->execute($values);
$Res = $CheckQuery->fetchAll(PDO::FETCH_ASSOC);
Now, this is great because given the IDs I want to be able to return:
ID1:0or1
ID2:0or1
I'm stuck trying to figure out how to return the IDs which do not exist in the database though. Any help here?
If you want 1 or 0, you can use the results of the $values array and the data from the database $Res, create arrays keyed on these lists (1's for $Res and 0's for $values) then overwrite the 0's with the 1's found in the database...
$present = array_fill_keys(array_column($Res, 'the_id'), 1);
$allValues = array_fill_keys($values, 0);
$result = array_replace($allValues, $present);
with some test data...
$_GET['id'] = '1,2,3';
$values = explode(",", $_GET['id']);
$Res = [ ['the_id' => 1], ['the_id' => 3]];
$present = array_fill_keys(array_column($Res, 'the_id'), 1);
$allValues = array_fill_keys($values, 0);
$result = array_replace($allValues, $present);
print_r($result);
you get
Array
(
[1] => 1
[2] => 0
[3] => 1
)
$values = explode(",", $_GET['id']);
$placeholders = str_repeat('?, ', count($values) - 1) . '?';
// select `the_id` as you don't need other fields in select
$CheckQuery = $database->prepare("SELECT the_id FROM users WHERE the_id IN($placeholders)");
$CheckQuery->execute($values);
// Use `FETCH_COLUMN` to fetch ids as array:
$ids = $CheckQuery->fetchAll(PDO::FETCH_COLUMN, 0);
// Now you can use `array_diff` to get ids
// that are in `$values` and not in `$ids`
print_r(array_diff($values, $ids));

Array to string conversion failed in PHP

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

How to iterate through database results, compare each value to that in an array and return the matching id?

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

How to insert array in single field

I want to store ids in database like this 1,2,3,4,5 in one field from a while loop.
how can i do this.
I am trying this way.
$array = array();
while($row=mysqli_fetch_assoc($result)){
$array[] = array($row['id']);
}
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$array')");
print_r($array);
This is showing error Array to string conversion and value as Array is inserted in database.
Please see and suggest any possible way to do this.
Thanks.
Create another table and insert 5 rows into it.
entity_id | ids
1 1
1 2
1 3
1 4
1 5
that's the only proper way of doing such things
However, if it's really a temp table, there is probably a way to avoid these inserts at all.
You can use either serialize or json_encode:
$data = serialize($array);
// ...or...
$data = json_encode($array);
If the array just contains plain numbers you can also use implode:
$data = implode(',', $array);
$arrays = array();
while($row=mysqli_fetch_assoc($result)){
$arrays[] = $row['id'];
}
$arr_str = implode(",", $arrays);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$arr_str')");
//print_r($array);
Detailed information about implode can be found here.
Use the implode() function:
$to_insert = implode(',', $array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$to_insert')");
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES(".join(',', $array).")");
Try:
$ids = join(',',$array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$ids')");
Please use implode function before insert into database :-
Here is a example :-
$array = array(1,2,3);
$comma_separated = implode(",", $array);
echo $comma_separated;
Output :-
1,2,3
In your case :-
$array = array();
while($row=mysqli_fetch_assoc($result)){
$array[] = array($row['id']);
}
$comma_separated = implode(",", $array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$comma_separated')");
print_r($array);
Set the field type varchar(255) and do this with php
$array = array();
$value = serialize($array);
$query = mysqli_query($connection,"INSERT INTO temp (temp) VALUES('$value')");
print_r($array);
To retrieve the value you should unserialize the column
$data = unserialize($result['temp']);
Here result is associative array. $data is an array you dont have to implode or explode or json_encode or json_decode

PHP - Add String to Array

I am wondering how I can add a string variable to the current array. For example, I have an array called $finalarray. Then I have a loop that adds a value on every run. Basically:
$finalarray = $results_array + string;
A very basic structure. I am using this for MySQL so that I can retrieve the final array of the column.
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray = $finalarray + $results_array["column"];
}
Edit:
Currently using this code (still not working):
$query = “SELECT * FROM table”;
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["name"];
}
echo $finalarray;
The problem is that it just says "Array"
Thanks,
Kevin
Answer to your edited question:
You cannot use just a single echo to print the entire array contents. Instead
Use
var_dump($finalarray);
or
print_r($finalarray);
to print the array contents..
Use the [] notation. + is for unioning two arrays.
$array = array('foo');
$array[] = 'bar'.
// $array == array('foo', 'bar')
You can use the function array_push or [] notation:
array_push($array, 'hi');
$array[] = 'hi';
Take a look at this
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["column"];
}
// Add X to the end of the array
$finalarray[] = "X";
Codaddict is correct. You are looking to output the last element that was added to the array.
echo end($final_array);
That will move the array's pointer to the last element added to it and then output it. Since you're adding the elements to the array in this manner...
$finalarray[] = $results_array["name"];
The key for each of your elements will be sequential, 0,1,2,3...so on and so forth. Another less elegant solution to get the last element would be...
echo $final_array[count($final_array) - 1];
echo implode($finalarray);
Or with a custom join "glue"
echo implode(', ', $finalarray);

Categories