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

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

Related

What is the convenient way of fetching array from DB to extract it then to vars in PHP?

I'm newbie learning PHP.
I have a MySQL table looking like this:
Working on fetching data from it using PDO.
My task?
I need to make arithmetic calculations between elements of this array. I.e.:
$sel_1_1 + $day, where $sel_1_1 is the first element of column select1
$sel_1_2 + $day, where $sel_1_2 is the second element of column select1
$sel_2_1 + $day, where $sel_1_2 is the first element of column select2
$sel_2_2 + $day, where $sel_1_2 is the second element of column select2
How I try to solve it
I need to fetch data from 4 columns (day, select1, select2, select3) in the form of array and to extract elements of these arrays into separate variables.
This is how I do:
$loged = 'test';
$stmt = $pdo->prepare("SELECT select1, select2, select3, day
FROM day_table
WHERE login=?");
$stmt->execute([$loged]);
$res = $stmt->fetchAll();
foreach ($res as $key=>$row) {
$sel1 = $row['select1'];
$sel2 = $row['select2'];
$sel3 = $row['select3'];
$day_from_db = $row['day'];
}
echo $sel1; // This fetches only the last element of "Select1" array.
echo $day_from_db; // Also fetches only the last element of "Day" array
echo "<pre>".print_r($res, true)."</pre>";
Output looks like this:
Array (
[0] => Array (
[select1] => 2
[select2] => 2
[select3] => 2
[birthday] => 2018-06-24 )
[1] => Array (
[select1] => 16
[select2] => 10
[select3] => 7
[birthday] => 2018-07-27 )
[2] => Array (
[select1] => 2
[select2] => 2
[select3] => 2
[birthday] => 2018-07-29 )
)
Then I try to extract my big array usung PHP extract:
$e = extract($res);
echo $e;
Returns 0.
And if I try doing in another manner like this:
// Fetch column day:
$sql = "SELECT day FROM day_table WHERE login=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$loged]);
$result = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$day0 = $result[0];
$day1 = $result[1];
$day2 = $result[2];
echo $day0."<br>";
echo $day1."<br>";
echo $day2."<br>";
// Fetch column select1:
$sql = "SELECT select1 FROM day_table WHERE login=?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$loged]);
$result = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
$select0 = $result[0];
$select1 = $result[1];
$select2 = $result[2];
echo $select0."<br>";
echo $select1."<br>";
echo $select2."<br>";
Returns desired values, but this is not good approach because:
If there are lots of elements in columns this becomes senselessly,
This is bad, non optimal code.
Can you please help me solving my issue with good, appropriate method?

WHERE IN array binding in DB::raw laravel 5.4

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

Insert new element in an array

EDITED
$queryPremium ="Select * from tablename where premium = 1 order by id desc";
$rowPremium = mysql_query($queryPremium);
$queryNotPremium ="Select * from tablename where premium = 0 order by id desc";
$rowNotPremium = mysql_query($queryNotPremium);
now i want a single array where the order of the rowNotPremium will be maintained and $rowPremium will be inserted randomly after 2 data of $rowNotPremium or after 3data of $rowNotPremium...
How to do that?
you can do this:
$newArray = $nonpremium + $premium
or
$newArray = array_merge($nonpremium, $premium)
Sorry for any bad practice here if you feel this can be edited please edit it...
<?php
$arr_a = array('1','2','3','4','5','6');
$arr_b = array('apples','oranges','bananas','peaches');
// How many elements are in the array we are inserting into
$count = count($arr_a);
// What was the last insert position? Make sure the next will be greater than this
$prev = 0;
// Loop through each of our elements to insert
foreach($arr_b as $value)
{
// Generate a random value, higher than the previous
// random number but still less than count($arr_a)
$rand = rand($prev, $count);
// Store this as the previous value + 1
$prev = $rand + 1;
// Insert our value into $arr_a at the random position
array_splice($arr_a, $rand, 0, $value);
}
echo "<pre>".print_r($arr_a, true)."</pre>";
Use array_splice() and rand() functions
$array1 = array( 1,2,3,4,5 );
$array2 = array( 6,7,8,9 );
array_splice( $array1, rand(0,count($array2)-1), 0, $array2 ); // splice in at random position

generate array for query string in php

Here I want to create an array for query string like given below:
item[]['item_id']=I00001&item[]['rate']=10.52&item[]['qty']=2&
item[]['item_id']=I52124&item[]['rate']=15.00&item[]['qty']=1&
item[]['item_id']=I62124&item[]['rate']=8.20&item[]['qty']=5
I want to generate it dynamically.
for($i = 0 ; $i< count($allitems) ;$i++){
$itemid = explode('~',$allitems[$i]);
$arrdet[]=["'item_id'"=>$itemid[0],"'rate'"=>$itemid[1],"'qty'" =>$itemid[2]];
$item['item'] = array_merge($arrdet);
//$item['item'][]=["'item_id'"=>$itemid[0],"'rate'"=>$itemid[1],"'qty'" =>$itemid[2]];
}
echo http_build_query($item);
but my result for this
item[0]['item_id']=I00001&item[0]['rate']=10.52&item[0]['qty']=2&
item[1]['item_id']=I52124&item[1]['rate']=15.00&item[1]['qty']=1&
item[2]['item_id']=I62124&item[2]['rate']=8.20&item[2]['qty']=5
How it Possible?
Thanks in advance
I did so much workarounds. But, it should actually works.
$countAllitems = count($allitems);
$arr = array();
$items = array();
$query = array();
for($i = 0 ; $i< $countAllItems; $i++){
$itemid = explode('~',$allitems[$i]);
$arr['item_id'] = $itemid[0];
$arr['rate'] = $itemid[1];
$arr['qty'] = $itemid[2];
//Assign the array to another array with key 'item[]'
$items['item[]'] = $arr;
//Build the array to http query and assign to another array
$query[] = http_build_query($items);
}
//Implode the stored http queries
echo implode('&', $query);
The array is zero-indexed internally.
$array = [1, 2, 3];
is internally
$array = [
0 => 1,
1 => 2,
2 => 3
]
The http_build_query will always output keys of the array, even if you do not specify them explicitly.

PHP - How to store distinct values so that while loop will not reiterate previous loops

I want my array to echo out only distinct values.
Here are my php codes so far:
$get_con = mysqli_query($con, "SELECT * FROM messages WHERE from_id='$my_id' OR to_id='$my_id' ");
$last_select_id = "";
while ($run_con = mysqli_fetch_array($get_con)) {
$from_id = $run_con['from_id'];
$to_id = $run_con['to_id'];
//This just ensures that it echos the other person's id and not my own
if ($from_id == $my_id) {
$select_id = $to_id;
} else {
$select_id = $from_id;}
//Trying to save the iterations
if ($select_id != $last_select_id) {
$last_select_id = $select_id;
echo "$select_id<br/>";
}
}
For example, my array has: 1, 1, 2, 3, 4, 2, 4.
My codes will return as: 1, 2, 3, 4, 2, 4
I want: 1, 2, 3, 4
The problem is that 2 and 4 are being repeated twice.
The statement, "if ($select_id != $last_select_id) {" is stopping "1" from being repeated twice in the beginning. This means that my if statement can only store $last_select_id only once for the previous iteration. I've searched for two days but couldn't find an answer. I would appreciate any help! Thank you.
There are a couple of approaches you can use.
In PHP, you can create an array, and place each entry into the array as it's returned/echoed/whatever.
$array = array( 1,1,2,3,4,4,5 );
$seen = array();
foreach ( $array as $arr ) {
if ( !in_array( $arr, $seen )) {
echo $arr.PHP_EOL;
$seen[] = $arr;
}
}
Of course, it's probably better to not have duplicate entries in the array, anyway. In PHP, you can use array_unique() for that:
$array = array( 1,1,2,3,4,4,5 );
$array = array_unique( $array );
foreach ( $array as $arr ) echo $arr.PHP_EOL;
But probably even better than THAT is to simply not have duplicates in your array to begin with. Look at "SELECT DISTINCT " in your SQL for that....
PHP has a function for this
array_unique($array)
Documentation here.
In your case it would be
$temp_array = array_unique(mysqli_fetch_array($get_con));
foreach($temp_array as $temp) {
*stuff*
}
I would use the SELECT DISTINCT statement in my query:
//I'm assuming you have a column called "id"
$get_con = mysqli_query($con, "SELECT DISTINCT id FROM messages WHERE from_id='$my_id' OR to_id='$my_id' ");
Info on SELECT DISTINCT can be found here: http://www.mysqltutorial.org/mysql-distinct.aspx
From there you can just do the following to output all the id's:
foreach($id in $get_con){
echo $id
}
You can also adjust for needs as you see fit.

Categories