MySql NOT IN many values from the mysql fetched result - php

I have 2 MySql queries which are interdependent.
My 'table1'
----------
id
----------
1
2
3
4
5
6
7
My First query
$sql1 = "SELECT * FROM table1 WHERE";// some condition which gives me id's 1,2,3
$res1=$obj->_executeQuery($sql1);
$res1=$obj->getAll($res1);
The result of this is giving me array
Array
(
[0] => Array
(
[id] => 1
..
..
)
[1] => Array
(
[id] => 2
..
..
)
[2] => Array
(
[id] => 3
..
..
)
)
I want to run another query on same 'table1', where not equal to list of ID's which i am getting from the first query.
My Second Query
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (" . implode(',', $res1) . ")";
This is not showing me only one id i,e first. In above case i should get id's 4,5,6,7

Since implode will not give the desired value on multidimensional array so first you need to get the array of all id's to form one-dimensional array then use implode on the array of id's:
$id=array();
foreach ($res1 as $key=>$inner_array){
$id[]= $inner_array['id'];
}
you can use array_walk also here like this:
array_walk($res1,function($c) use (&$id) {$id[] = $c['id'];});
but i think the best one is array_map :
$id = array_map(function($i) {
return $i['id'];
}, $res1);
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (" . implode(',', $id) . ")";
Note: when ever you are doing select please specify your column if you need few to select,unnecessarily selecting all will slow your sql processing.
suppose here:SELECT * FROM table1 WHERE, if you need only id then please select id only.

You have to change $res1, which is a two-dimensional array, into a one-dimensional array of IDs to be able to use implode:
$ids_from_first_query = array();
foreach($res1 as $result_row) {
$ids_from_first_query[] = $result_row['id'];
}
$ids_as_string = implode(',', $ids_from_first_query);
$sql2 = 'SELECT * FROM table1 WHERE id NOT IN(' . $ids_as_string . ')';
In the above code, $ids_as_string will look like this:
1,2,3
Thus it can be used in your MySQL query

Here you are getting two dimensional array so that's reason it is not working
while($each=mysql_fetch_array($res1))
{
$array[]=$each[id];
}
$imp=implode(",",$array);
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (".$imp.")";
Try this it will works

Related

PHP SQL - Search for match with same players

Good mornin'.
I've been tryin to make "something" that will compare matchup percentage but i'm stuck'd at searching for matches with 2 same players.
I've found something about AND OR parenthesis so here is my sql query
$ccc = "SELECT * FROM zapasy WHERE (playerName01 = '".$player1."' OR playerName01 ='".$player2."') AND (playerName02 = '".$player2."' OR playerName02='".$player1."')";
$result3 = $db->query($ccc);
$ids = array();
while ($row55 = $result3->fetch_assoc())
{
$ids[] = $row55['winner'];
}
But , the problem is whenever i try to get data , it gives me more indexes than actualy expected.
This is the result of printing array values after fetching.
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 )
As expected is only 2 3 4 as u can see in the DB sample here.
db sample
Anyone suggestions on what i'm doing wrong?
A simple way to write this in MySQL uses tuples:
where (?, ?) in ( (playername01, playername02), (playername02, playername01) )
The ? are for parameters. That should be the way that you pass values into queries.
You are doing wrong while using AND OR in where clause
$ccc = "SELECT * FROM zapasy WHERE (playerName01 = '".$player1."' AND playerName02 ='".$player2."') OR (playerName01 = '".$player2."' AND playerName02='".$player1."')";
Try this #Patrik Dano

PHP / mySQL - in_array and Get Result

I have an array like below and that array refers to another data on my db,
Array
(
[0] => 4
[1] => 1
[2] => 15
[3] => 1
[4] => 1
)
how do I want to select value no 1, and get the most top value from table that has value=1?
I use in_array(1,$array) but it does not output anything. Below are my coding;
$sql = " Select * FROM table_name WHERE staff_id='".$_SESSION['staff_id']."' ORDER BY table_name DESC ";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
$leave_id= array();
while($row_permohonan=mysqli_fetch_assoc($result_permohonan))
{
$leave_available = $row_permohonan['leave'];
$leave_id[] = $row_permohonan['leave_id'];
} mysqli_free_result($result_permohonan);
//echo '<pre>'; print_r($leave_id); echo '</pre>';
if(in_array(1,$leave_id)){
echo $leave_available .'/'.$row['total_leave'];
}
I think you have missed $result.
$sql = " Select * FROM table_name WHERE staff_id='".$_SESSION['staff_id']."' ORDER BY table_name DESC ";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
$leave_id= array();
while($row_permohonan=mysqli_fetch_assoc($result)) //Here
{
$leave_available = $row_permohonan['leave'];
$leave_id[] = $row_permohonan['leave_id'];
} mysqli_free_result($result); //And here
First, your code is not clear. You are using:
echo $leave_available.'/'.$row['total_leave'];
Where "$row" is not set anywhere into your code. If you have put on top of your code:
ini_set("display_errors", "On"); error_reporting(E_ALL);
PHP would break with a fatal error if you are executing the code exactly as you gave it. But I assume that you set it somewhere else into your code.
2nd: You should return the data you want into your MySQL query. If you just want to know if there is at least 1 row into your database having leave_id=1 and staff_id=$_SESSION['staff_id'], then add this condition in your SQL query:
$sql = "Select COUNT(*) AS nbrows FROM table_name WHERE staff_id='".$_SESSION['staff_id']."' AND leave_id=1 ORDER BY column_name DESC ";
And then: you have to use "ORDER BY" statement with a column name and not the table name.
Using "in_array": as you are matching "1", I would recommend you to add "true" as 3rd parameter of this function (force using "strict comparison" in case sensitive and type matching):
in_array(1, $array, true)
Then, you'll also have to cast your $leave_id result:
$leave_id[] = (int)...
(int) cast the string value to integer (as PHP results from database are almost strings)

mysql select multiple values from array match

I have an array lets say: Array ( [0] => 9 [1] => 7 [2] => 8 )
I want to SELECT from a table (users) all phone numbers where userID matches one from the array (if there is a phone number listed).
I want to do this without selecting all of the users from the database and only those that match that of the array and with actual phone numbers, should I do this in a loop?
Typically when I am doing an UPDATE, I do them within a foreach loop. Like so:
foreach($userArr as $user) {
$pid = $user;
if(!$statement->execute()) {
throw new Exception($statement->error, $statement->errno);
}
}
$statement->close();
Can we do SELECT like that as well?
Thanks in advance for any advice.
If you want to select all these users, just do the follow:
$idList = implode(',', $yourArray);
$sql = "SELECT * FROM users WHERE id IN($idList)";
// execute this $sql query
Try this:
<?php
$array = array(9, 7, 8);
$query = "SELECT * FROM mytable WHERE id = ";
$condition = implode(' OR id = ', $array);
$query .= $condition;
echo $query;
?>
Output:
SELECT * FROM mytable WHERE id = 9 OR id = 7 OR id = 8
You should do the following:
Build a string to express the userid seperated by comma. - Loop will be needed. i.e id1, id2, id3
Build the query string to search for them.
Example:
SELECT * FROM `Users` WHERE id IN (id1, id2, id3)

How to find data when results set is in array?

i want to find data through id, i have an array like that
$result=
Array
(
[3] => 536371014
[38] => 1435902884
[53] => 100000224980743
)
user _id is
[3], [38], [53]
in my user tabe
user_id name
3 usii
38 test
53 test 2
i want to find all data through user id, how can i do that with the result set user id which is index, i tried alot but didn't get success, please help me to do that, thanks a ton in advance.
Use foreach like this
foreach($result as $val) {
echo $val[$user_id];
}
Something like this should work (brutal pseudo code)
in_list = implode(", ", array_keys($result));
$all_users = mysql.query("select * from user_table where user_id in (" . in_list . ");";
array_keys should give you an array of just the indexes used (3, 38 and 53)
implode with ", " as glue should give you a string like this "3, 38, 53" suitable for a mysql IN condition.
$user_ids = implode(",",array_keys($result));
$query = "SELECT * FROM usertable WHERE user_id IN (".$user_ids.")";

How to get the result of a query with values in a array?

This is my function where i fetch my results from database
function Prof_Viewer($MemberId)
{
$query = $this->db->query("SELECT distinct(t1.dProfileId) as prof
FROM tbl_profile_viewer as t1
JOIN tbl_login as t2
WHERE t1.dProfileViwerId='$MemberId'");
if($query->num_rows > 0)
{
foreach($query->result() as $row)
{
echo $row->prof;//i am receiving many values here
$query1 = $this->db->query("SELECT distinct(t3.dUser_name),t2.dPath,t3.dCreatedDate
FROM tbl_login as t3
JOIN tbl_profile_viewer as t1,
tbl_member_details as t2
WHERE t3.dMember_Id = '$row->prof'
AND t2.dMember_Id ='$row->prof'");
}
return $query1->result_array();
}
}
As commented above i receive many values while echo the variable $row->prof;
say i have values such as 1 2 and 3.......
Even if i have these three values my 'query1' takes only the last value .so i have only one result i want the query to be executed for 1 and 2 also
how to Achieve that
You can just use PHP's explode() to convert your string into an array. For example:
<?php
$str = 'one|two|three|four';
// positive limit
print_r(explode('|', $str));
// gives you an array:
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
)
?>
But I think you would be better off if you learned how to do JOIN's:
http://en.wikipedia.org/wiki/Join_(SQL)
I'm assuming you're using mysqli here.
Result_fetch_array() will do what you want
http://au2.php.net/manual/en/mysqli-result.fetch-array.php

Categories